python遍历指定文件夹的所有文件_python 统计指定文件夹下所有的文件数量,BFS方式...
python 統計指定文件夾下所有的文件數量
本來一直是有這個需求,只是以前寫的是遞歸的方式處理,感覺對資源的占用不友好,而且python的最大遞歸深度不超過1000,所以改了一下,這里用廣度優先遍歷的方式實現。
實測兩層共24個文件夾,共50w的文件數量。運行時間大概3秒。以下是代碼:
import os
import queue
def get_file_quantity(folder: str) -> int:
'''BFS獲取文件夾下文件的總數量'''
# 判斷初始文件夾
assert os.path.isdir(folder), '請輸入有效的文件夾參數'
file_quantity = 0 # 初始化文件數量
folder_path_queue = queue.Queue()
folder_path_queue.put_nowait(folder) # 初始化隊列的值
# 處理隊列里的文件夾
while not folder_path_queue.empty():
folder = folder_path_queue.get_nowait()
file_folder_list = list(map(lambda bar: os.path.join(folder, bar), os.listdir(folder)))
folder_list = list(filter(lambda bar: os.path.isdir(bar), file_folder_list))
for folder_path in folder_list:
folder_path_queue.put_nowait(folder_path)
temp_file_count = len(file_folder_list) - len(folder_list)
file_quantity += temp_file_count
return file_quantity
if __name__ == '__main__':
file_quantity = get_file_quantity(r'/home')
print(f'文件總數是: {file_quantity}')
思路
這里主要是使用了隊列,就是普通的BFS的思路
這里稍微改一下folder_list = list(filter(lambda bar: os.path.isdir(bar), file_folder_list))里的的lambda函數就可以實現判斷對文件名的各種判斷操作,這里函數功能的實現就完全取決于自己的腦洞了!
附上一個改編版: 查看包含特定后綴的文件的數量
改編版: 查看包含特定后綴的文件的數量
import os
import queue
def filter_extension(filename: str, extension: str) -> bool:
'''判斷文件路徑名的后綴是否和給定的后綴字符串相同
只是單純的字符串判斷
'''
basename_and_extension = filename.split('.')
return (basename_and_extension[-1] == extension) and (len(basename_and_extension) >= 2)
def get_file_quantity(folder: str, extension: str) -> int:
'''BFS獲取文件夾下文件的總數量'''
# 判斷初始文件夾
assert os.path.isdir(folder), '請輸入有效的文件夾參數'
assert isinstance(extension, str), '請輸入有效的文件后綴名'
file_quantity = 0 # 初始化文件數量
folder_path_queue = queue.Queue()
folder_path_queue.put_nowait(folder) # 初始化隊列的值
# 處理隊列里的文件夾
while not folder_path_queue.empty():
folder = folder_path_queue.get_nowait()
file_folder_list = list(map(lambda bar: os.path.join(folder, bar), os.listdir(folder)))
folder_list = list(filter(lambda bar: os.path.isdir(bar), file_folder_list))
file_list = list(filter(lambda bar: os.path.isfile(bar), file_folder_list))
match_extension_list = list(filter(lambda bar: filter_extension(bar, extension), file_list))
for folder_path in folder_list:
folder_path_queue.put_nowait(folder_path)
temp_file_count = len(match_extension_list)
file_quantity += temp_file_count
return file_quantity
if __name__ == '__main__':
extension = 'py'
file_quantity = get_file_quantity(r'/home', extension)
print(f'包含后綴 {extension } 的文件的數量: {file_quantity}')
總結
以上是生活随笔為你收集整理的python遍历指定文件夹的所有文件_python 统计指定文件夹下所有的文件数量,BFS方式...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: office是不是python的打开方式
- 下一篇: python mql4_可以转发文章不?