gpt4 book ai didi

python计算目录中大小特定类型的文件txt

转载 作者:太空宇宙 更新时间:2023-11-04 09:59:43 24 4
gpt4 key购买 nike

在我的文件夹中,有两种类型的文件: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

关于python计算目录中大小特定类型的文件txt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44249391/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com