[英]python count size specific type file txt in a directory
在我的文件夾中,有兩種類型的文件: html
和txt
。 我想知道txt
文件的總大小。
我找到了此代碼,但是如何將其應用於我的需要?
import os
from os.path import join, getsize
size = 0
count = 0
for root, dirs, files in os.walk(path):
size += sum(getsize(join(root, name)) for name in files)
count += len(files)
print count, size
您可以通過對以下內容添加if
來限定哪些文件:
for root, dirs, files in os.walk(path):
size += sum(getsize(join(root, name)) for name in files if name.endswith('.txt'))
count += sum(1 for name in files if name.endswith('.txt'))
print count, size
最好使用glob( https://docs.python.org/3/library/glob.html )代替os來查找文件。 這使恕我直言更具可讀性。
import glob
import os
path = '/tmp'
files = glob.glob(path + "/**/*.txt")
total_size = 0
for file in files:
total_size += os.path.getsize(os.path.join(path, file))
print len(files), total_size
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.