我的文件系统上有以下目录结构:
/home/myUser/
stuff_home/
fizz/
a.txt
b.txt
buzz/
1.pdf
widgets/
c.txt
2.pdf
3.pdf
4.pdf
我想stuff_home/
递归遍历并计算它包含的子目录、.txt
文件和.pdf
文档的数量。我写了一个小的 Python 脚本:
import os
dirCnt = 0
txtCnt = 0
pdfCnt = 0
def main():
get_counts("/home/myUser/stuff_home")
t = str(txtCnt)
p = str(pdfCnt)
d = str(dirCnt)
print "\nRESULTS\Text Files:\t" + t + "\nPDF Files:\t" + p + "\nDirectories:\t" + d + "\n\n"
def get_counts(root):
contents = os.listdir(root)
for file in contents:
if os.path.isdir(file):
dirCnt = dirCnt + 1
elif os.path.splitext(file)[1] == "txt":
txtCnt = txtCnt + 1
elif os.path.splitext(file)[1] == "pdf":
pdfCnt = pdfCnt + 1
else:
print "Encountered unknown file: " + file
当我运行它时,我没有收到任何错误,但脚本显然编码错误。这是我得到的输出:
Encountered unkown file: fizz
Encountered unkown file: buzz
Encountered unkown file: widgets
RESULTS
Text Files: 0
PDF Files: 0
Directories: 0
有什么让你们 Pythonians 跳出来的吗?看起来我的任何逻辑(用于检测文件与目录,以及splitext
用于获取文件扩展名)都在这里工作......提前致谢!