I would like to learn how to count when os.walk enters into another subfolder. 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..
import pathlib
path = pathlib.Path('articles')
subfolder_count = len(path.glob("**/"))
count = len(path.glob("**/*.pdf"))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.