如何通过目录和子文件夹进行计算

问题描述 投票:0回答:1

我有一个主目录,其中有9个子文件夹。在每个文件的内部,有1000个文件。我需要做一个for循环来读取主目录和文件夹,但是问题是,子文件夹的名称不相似并且没有分子,所以被卡住了。我已经看过Iterate through folders, then subfolders and print filenames with path to text file,但无法区分如何开始。我的努力如下:

import os                                                                                                             

for root, dirs, files in os.walk(r'\Desktop\output\new our scenario\test'):
     for file in files:
        with open(os.path.join(root, file), "r") as auto:
            ##Doing Whatever I want

但是它不正确并且不起作用。

python directory directory-structure
1个回答
0
投票

你知道glob吗?那可能是解决您的问题的方法。

您可以使用通配符路径名获得子目录中所有文件的列表,例如:

这里是循环遍历txt文件的示例,但您不必将其限制为文件类型。但是,如果最后不使用*.*,它也会列出目录[]

import glob

file_list = glob.glob('known_dir/*/*.txt')

for file in file_list:
    with open(file, "r") as auto:
         ##Doing Whatever you want
© www.soinside.com 2019 - 2024. All rights reserved.