我正在尝试计算特定文件夹中的文件数量,这些文件遍及大量的父目录。每个项目包含相同的文件夹结构:
C:/Projects
2019
Project A
Communication
Images
Project B
Communication
Images
...
2018
...下面是我的尝试
base_dir = 'C:/Projects/'
years = ['2019', '2018', '2017']
image_folder = '/Communication/Images'
project_list = []
for project in project_list:
for year in years:
target_folder = base_dir + year + project + image_folder
for root, dirs, files in os.walk(folder):
total += len(files)
# Print to CSV etc首先,我需要获取指向image文件夹的所有路径的列表。我正在努力理解的(即使是尝试工作)是os.walk接受根、目录、文件。os.walk可以在不陷入3For循环的情况下做我需要的事情吗?有很多我想要统计的文件,所以我想确保我不会因为按照我的方式组织它而影响性能
发布于 2019-02-20 03:47:02
Python3的pathlib在这类事情上相当灵巧:
from pathlib import Path
base_dir = Path('C:/Projects/')
# rglob = recursive glob; finds all files in all subdirectories
files_generator = base_dir.rglob("*")
total_n_files = len(list(files_generator))你甚至可以通过target_folder (使用你问题中的文件结构)获得一个包含文件计数的字典,如下所示:
from collections import Counter
base_dir = Path('C:/Projects/')
file_counts = Counter(p.parent for p in base_dir.rglob("*"))(第二个代码片段改编自https://realpython.com/python-pathlib/上的几个示例)
https://stackoverflow.com/questions/54773330
复制相似问题