[英]Counting subfolders using OS.Walk() in python
I would like to learn how to count when os.walk enters into another subfolder.我想学习当 os.walk 进入另一个子文件夹时如何计数。 Right now I am able to count the number of files in filenames, but when it switches from the starting directory to another subfolder directory, I would like a count to be added to the subfolder.现在我能够计算文件名中的文件数,但是当它从起始目录切换到另一个子文件夹目录时,我希望将一个计数添加到子文件夹中。 I am not sure the best way to do this.我不确定这样做的最佳方法。 Any help is greatly appreciated.任何帮助是极大的赞赏。
count = 0
subfolder_count = 0
for foldername, subfolders, filenames in os.walk('articles'):
for file in filenames:
if file.endswith('.pdf'):
count += 1
You're already iterating, just keep iterating!你已经在迭代了,继续迭代!
count = 0
subfolder_count = 0
for root, dirs, files in os.walk('articles'):
for dir_ in dirs:
subfolder_count += 1
for file_ in files:
if file_.endswith('.pdf'):
count += 1
In modern Python (3.4+) you don't even need os.walk
, because pathlib
has you covered for the small overhead of traversing the tree twice..在现代 Python (3.4+) 中,您甚至不需要os.walk
,因为pathlib
已经涵盖了两次遍历树的小开销。
import pathlib
path = pathlib.Path('articles')
subfolder_count = len(path.glob("**/"))
count = len(path.glob("**/*.pdf"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.