国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Python > 正文

利用Python查看目錄中的文件示例詳解

2020-02-16 02:08:31
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

前言

我們?cè)谌粘i_(kāi)發(fā)中,經(jīng)常會(huì)遇到一些關(guān)于文件的操作,例如,實(shí)現(xiàn)查看目錄內(nèi)容的功能。類(lèi)似Linux下的tree命令。統(tǒng)計(jì)目錄下指定后綴文件的行數(shù)。

功能是將目錄下所有的文件路徑存入list中。可以加入后綴判斷功能,搜索指定的后綴名文件。主要利用遞歸的方法來(lái)檢索文件。

仿造 tree 功能示例代碼

Python2.7

列出目錄下所有文件

遞歸法

import osdef tree_dir(path, c_path='', is_root=True): """ Get file list under path. Like 'tree' :param path Root dir :param c_path Child dir :param is_root Current is root dir """ res = [] if not os.path.exists(path): return res for f in os.listdir(path): if os.path.isfile(os.path.join(path, f)):  if is_root:  res.append(f)  else:  res.append(os.path.join(c_path, f)) else:  res.extend(tree_dir(os.path.join(path, f), f, is_root=False)) return res

下面是加入后綴判斷的方法。在找到文件后,判斷一下是否符合后綴要求。不符合要求的文件就跳過(guò)。

def tree_dir_sur(path, c_path='', is_root=True, suffix=''): """ Get file list under path. Like 'tree' :param path Root dir :param c_path Child dir :param is_root Current is root dir :param suffix Suffix of file """ res = [] if not os.path.exists(path) or not os.path.isdir(path): return res for f in os.listdir(path): if os.path.isfile(os.path.join(path, f)) and str(f).endswith(suffix):  if is_root:  res.append(f)  else:  res.append(os.path.join(c_path, f)) else:  res.extend(tree_dir_sur(os.path.join(path, f), f, is_root=False, suffix=suffix)) return resif __name__ == "__main__": for p in tree_dir_sur(os.path.join('E:/ws', 'rnote', 'Python_note'), suffix='md'): print p

統(tǒng)計(jì)目錄下指定后綴文件的行數(shù)

僅適用os中的方法,僅檢索目錄中固定位置的文件

# -*- coding: utf-8 -*-import osdef count_by_categories(path): """ Find all target files and count the lines """ if not os.path.exists(path): return c_l_dict = dict() # e.g. {category: lines} category_list = [cate for cate in os.listdir(path) if   os.path.isdir(os.path.join(path, cate)) and not cate.startswith('.')] for category_dir in category_list: line_count = _sum_total_line(os.path.join(path, category_dir), '.md') if line_count > 0:  c_l_dict[category_dir] = line_count return c_l_dictdef _sum_total_line(path, endswith='.md'): """ Get the total lines of target files """ if not os.path.exists(path) or not os.path.isdir(path): return 0 total_lines = 0 for f in os.listdir(path): if f.endswith(endswith):  with open(os.path.join(path, f)) as cur_f:  total_lines += len(cur_f.readlines()) return total_linesif __name__ == '__main__': note_dir = 'E:/ws/rnote' ca_l_dict = count_by_categories(note_dir) all_lines = 0 for k in ca_l_dict.keys(): all_lines += ca_l_dict[k] print 'all lines:', str(all_lines) print ca_l_dict            
發(fā)表評(píng)論 共有條評(píng)論
用戶(hù)名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 闽清县| 吴桥县| 德庆县| 莱芜市| 吉安县| 阿拉善左旗| 如东县| 邯郸县| 汉中市| 大安市| 民县| 广水市| 宁晋县| 巴彦县| 龙山县| 淮阳县| 定陶县| 兰坪| 乐山市| 贺州市| 黄冈市| 台北县| 蒙城县| 东兰县| 九龙县| 拜泉县| 盖州市| 潜山县| 正阳县| 商都县| 德化县| 崇礼县| 酉阳| 紫阳县| 洪雅县| 广河县| 揭东县| 浦县| 濮阳县| 梁河县| 化隆|