【问题标题】:How to do computations through directory and subfolders如何通过目录和子文件夹进行计算
【发布时间】:2020-09-07 21:59:46
【问题描述】:

我有一个包含 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

但它不正确,不起作用。

【问题讨论】:

  • 这能回答你的问题吗? How to read a directory and sub-folders python
  • 请避免一次又一次地问同样的问题。
  • '\Desktop\output\new our scenario\test' 不太可能存在于您的 PC 上,请再次检查。
  • @lenik 现在,我必须删除这个问题,否则我可以保留它,你有什么建议?

标签: python directory directory-structure


【解决方案1】:

你知道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

【讨论】:

    猜你喜欢
    • 2015-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    相关资源
    最近更新 更多