【发布时间】:2015-11-26 12:49:51
【问题描述】:
我想遍历目录中的子目录并获取每个子目录中的文件数。我的(凌乱的)解决方案如下所示:
import os, sys
import subprocess
def Count_files_in_subd():
for root, dirs, files in os.walk("/Path/to/directory", topdown=False):
for name in dirs:
print name
f = os.path.join(root, name)
os.chdir(f)
i=0
for filename in os.listdir(os.getcwd()):
i+=1
print i
Count_files_in_subd()
脚本首先依次查看目录中的子目录,然后更改它正在“查看”的目录,以计算其中的文件。
它有效,但我知道在 python 中有更好的方法来做到这一点。我查看了关于 SO 的不同问题,但是当我尝试大多数解决方案时,每个子目录的文件数只有一个,并且我假设该目录被计为文件。任何有关如何更好地做到这一点的帮助将不胜感激。
【问题讨论】:
标签: python count directory subdirectory