簡體   English   中英

目錄中的python計數大小特定類型文件txt

[英]python count size specific type file txt in a directory

在我的文件夾中,有兩種類型的文件: htmltxt 我想知道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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM