蟒蛇计数大小特定类型文件txt在一个目录中
在我的文件夹中,有两种类型的文件:html
和txt
。 我想知道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
的内涵像资格哪些文件:不是OS
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
适用于大小,但你的第三行显示“名称”的红线:未解决的参考名称。 NameError:未定义全局名称'name'。我需要使name =''? –
好吧,文件中的_为1。我将_替换为名称。然后工作,谢谢 –
更好地利用水珠(https://docs.python.org/3/library/glob.html)找到你的文件。这使得它更具可读性。
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
这也适用 –
对于文件中的名称,如果名称在'.txt'中 - 在末尾添加。但是,os路径也有一个本地命令,我不记得了。我可以看看,当我在计算机。) –
.endswith是你需要的:) –