亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

 更新時間:2017年08月28日 08:34:25   作者:RustFisher  
這篇文章主要給大家介紹了關于利用Python查看目錄中的文件,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面跟著小編來一起學習學習吧。

前言

我們在日常開發(fā)中,經常會遇到一些關于文件的操作,例如,實現(xiàn)查看目錄內容的功能。類似Linux下的tree命令。統(tǒng)計目錄下指定后綴文件的行數。

功能是將目錄下所有的文件路徑存入list中??梢约尤牒缶Y判斷功能,搜索指定的后綴名文件。主要利用遞歸的方法來檢索文件。

仿造 tree 功能示例代碼

Python2.7

列出目錄下所有文件

遞歸法

import os
def 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

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

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 res
if __name__ == "__main__":
 for p in tree_dir_sur(os.path.join('E:\ws', 'rnote', 'Python_note'), suffix='md'):
 print p

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

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

# -*- coding: utf-8 -*-
import os
def 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_dict
def _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_lines
if __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

以筆記文件夾為例,分別統(tǒng)計分類目錄下文件的總行數,測試輸出

all lines: 25433
{'flash_compile_git_note': 334, 'Linux_note': 387, 'Algorithm_note': 3637, 'Comprehensive': 216, 'advice': 137, 'Java_note': 3013, 'Android_note': 11552, 'DesignPattern': 2646, 'Python_note': 787, 'kotlin': 184, 'cpp_note': 279, 'PyQt_note': 439, 'reading': 686, 'backend': 1136}

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。

相關文章

  • Python數據分析?Numpy?的使用方法

    Python數據分析?Numpy?的使用方法

    這篇文章主要介紹了Python數據分析?Numpy?的使用方法,Numpy?是一個Python擴展庫,專門做科學計算,也是大部分Python科學計算庫的基礎,關于其的使用方法,需要的小伙伴可以參考下面文章內容
    2022-05-05
  • python3新特性函數注釋Function Annotations用法分析

    python3新特性函數注釋Function Annotations用法分析

    這篇文章主要介紹了python3新特性函數注釋Function Annotations用法,結合實例形式分析了Python3函數注釋的定義方法與使用技巧,需要的朋友可以參考下
    2016-07-07
  • python開發(fā)sdk模塊的方法

    python開發(fā)sdk模塊的方法

    這篇文章主要介紹了python開發(fā)sdk模塊,通過setup.py將框架安裝到python環(huán)境中,開發(fā)成第三方模塊來,?以此來調用,增加使用方便及安全高效性,需要的朋友可以參考下
    2022-07-07
  • Python尋找路徑和查找文件路徑的示例

    Python尋找路徑和查找文件路徑的示例

    今天小編就為大家分享一篇Python尋找路徑和查找文件路徑的示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07
  • Python之np.where()如何替換缺失值

    Python之np.where()如何替換缺失值

    這篇文章主要介紹了Python中的np.where()如何替換缺失值問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-02-02
  • Python實現(xiàn)合并excel表格的方法分析

    Python實現(xiàn)合并excel表格的方法分析

    這篇文章主要介紹了Python實現(xiàn)合并excel表格的方法,結合實例形式分析了Python合并Excel表格的原理、實現(xiàn)步驟與相關操作技巧,需要的朋友可以參考下
    2019-04-04
  • Python 實現(xiàn)使用空值進行賦值 None

    Python 實現(xiàn)使用空值進行賦值 None

    這篇文章主要介紹了Python 實現(xiàn)使用空值進行賦值 None,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-03-03
  • Python+uiautomator2實現(xiàn)手機鎖屏解鎖功能

    Python+uiautomator2實現(xiàn)手機鎖屏解鎖功能

    python-uiautomator2封裝了谷歌自帶的uiautomator2測試框架,提供便利的python接口,這篇文章給大家介紹使用Python+uiautomator2實現(xiàn)手機鎖屏解鎖(期望輸入的鎖屏密碼,基于滑動解鎖),感興趣的朋友一起看看吧
    2021-04-04
  • python如何爬取動態(tài)網站

    python如何爬取動態(tài)網站

    在本篇內容里小編給各位分享了關于python如何爬取動態(tài)網站的相關知識點內容,有興趣的朋友們可以參考下。
    2020-09-09
  • 使用python執(zhí)行shell腳本 并動態(tài)傳參 及subprocess的使用詳解

    使用python執(zhí)行shell腳本 并動態(tài)傳參 及subprocess的使用詳解

    這篇文章主要介紹了使用python執(zhí)行shell腳本 并動態(tài)傳參 及subprocess的使用詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-03-03

最新評論