我正在嘗試計算檔案夾及其所有子檔案夾中的所有檔案例如,如果我的檔案夾如下所示:
file1.txt
subfolder1/
├── file2.txt
├── subfolder2/
│ ├── file3.txt
│ ├── file4.txt
│ └── subfolder3/
│ └── file5.txt
└── file6.txt
file7.txt
我想要7號。
我嘗試的第一件事是一個遞回函式,它計算所有檔案并為每個檔案夾呼叫自身
def get_file_count(directory: str) -> int:
count = 0
for filename in os.listdir(directory):
file = (os.path.join(directory, filename))
if os.path.isfile(file):
count = 1
elif os.path.isdir(file):
count = get_file_count(file)
return count
這種方式有效,但需要大量時間來處理大目錄。
我還記得這篇文章,它顯示了一種使用 win32com 計算檔案夾總大小的快速方法,我想知道這個庫是否也提供了一種方法來做我正在尋找的事情。但是經過搜索,我只找到了這個
fso = com.Dispatch("Scripting.FileSystemObject")
folder = fso.GetFolder(".")
size = folder.Files.Count
但這僅回傳目標檔案夾(而不是其子檔案夾)中的檔案數
那么,您知道python中是否有一個最佳函式可以回傳檔案夾及其所有子檔案夾中的檔案數嗎?
uj5u.com熱心網友回復:
IIUC,你可以做到
sum(len(files) for _, _, files in os.walk('path/to/folder'))
或者,為了避免len可能稍微更好的性能:
sum(1 for _, _, files in os.walk('folder_test') for f in files)
uj5u.com熱心網友回復:
此代碼將顯示來自指定根的所有非目錄(例如,純檔案、符號鏈接)的目錄條目的計數。
包括時間和測驗中使用的實際路徑名:
from glob import glob, escape
import os
import time
def get_file_count(directory: str) -> int:
count = 0
for filename in glob(os.path.join(escape(directory), '*')):
if os.path.isdir(filename):
count = get_file_count(filename)
else:
count = 1
return count
start = time.perf_counter()
count = get_file_count('/Volumes/G-DRIVE Thunderbolt 3')
end = time.perf_counter()
print(count)
print(f'{end-start:.2f}s')
輸出:
166231
2.38s
uj5u.com熱心網友回復:
我用過 os.walk()
這是我的樣品,我希望它會幫助你
def file_dir():
directories = []
res = {}
cwd = os.getcwd()
for root, dirs, files in os.walk(cwd):
for file in files:
if file.endswith(".tsv"):
directories.append(os.path.join(root, file))
res['dir'] = directories
return res
uj5u.com熱心網友回復:
也可以直接使用命令:
find DIR_NAME -type f | wc -l
這將回傳所有檔案的計數os.system()這可以從 python 完成。
uj5u.com熱心網友回復:
使用庫os和的另一個解決方案Path:
from pathlib import Path
from os.path import isfile
len([x for x in Path('./dir1').rglob('*') if isfile(x)])
uj5u.com熱心網友回復:
正確的方法是os.walk像其他人指出的那樣使用,但要提供另一種盡可能類似于您原來的解決方案:
您可以使用os.scandir來避免構建整個串列的成本,它應該會更快:
def get_file_count(directory: str) -> int:
count = 0
for entry in os.scandir(directory):
if entry.is_file():
count = 1
elif entry.is_dir():
count = get_file_count(os.path.join(directory, entry.name))
return count
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/476865.html
標籤:Python python-3.x 文件 目录 子目录
上一篇:如何從PC解壓縮zip檔案
