【问题标题】:How to walk through subfolders individually?如何单独浏览子文件夹?
【发布时间】:2019-03-04 19:36:51
【问题描述】:

实际上我有一个文件夹(下图中的数据),其中包含 2 个子文件夹,每个子文件夹都包含一些 .png 文件。我需要遍历每个子文件夹并对该子文件夹中的每个图像文件进行一些编码并保存结果。我使用过os.walk()os.listdir()glob.glob(),但它们都不起作用。我尝试过的许多代码之一与以下相同:

path1 = Path('./data')
path2 = os.listdir(path1)

# loop through main folder to read each subfolder
for i in path2:
    if not i.startswith('.'):
       path3 = Path(os.path.join(path1,i))
       path4 = os.listdir(path3)

    #loop through each subfolder to read each file
       for j in path4:
           #some coding

enter image description here

任何建议将不胜感激。

【问题讨论】:

  • 为什么os.walk 解决方案不起作用?您是否尝试模仿 the docs 中的示例?

标签: python glob subdirectory os.walk listdir


【解决方案1】:

我建议使用pathlib 库。该库是一个“面向对象的文件系统路径”模块,它结合了 Python 最好的文件系统模块,如 os、os.path 和 glob。

from pathlib import Path

path1 = Path('./data')
files = [item.as_posix() for item in path1 .glob('**/*.png') if item.is_file()]

这将为您提供数据子文件夹中所有 .png 路径的列表。

【讨论】:

  • 感谢您的回答,但我不需要将所有图像文件放在一起。我正在尝试访问每个子文件夹以处理相关的图像文件。通过使用您的代码,我将无法分别循环遍历子文件夹。
  • 我不清楚您的确切意思,但您始终可以使用 .parent 方法将父文件夹作为每个文件路径的值
【解决方案2】:

os.walk 这样的东西:

import os
for root, dirs, files in os.walk(path_to_data_folder):
#    if not root.endswith(good_folder_name):
#        continue
    for fname in files:
        if fname_meets_my_criteria:
            fpath = os.path.join(root, fname)
            with open(fpath, 'r') as f, open(new_file_path, 'w') as newfile:
                data = f.read()
                # process file data
                new_data = func_that_processes_data(data)
                newfile.write(new_data)

这有点伪代码:

  • fname_meets_my_criteria 是比较的替代品,如果您想过滤文件进行处理,它需要这个 - 它可能类似于 fname.edswith('.txt')not fname.endswith('.cfg')

  • new_file_path 是新文件的路径和名称,处理后的数据将写入该文件。


如果您打算在处理完文件后覆盖这些文件,请改用:

for root, dirs, files in os.walk(path_to_data_folder):
#    if not root.endswith(good_folder_name):
#        continue
    for fname in files:
        if fname_meets_my_criteria:
            fpath = os.path.join(root, fname)
            with open(fpath, 'r') as f:
                data = f.read()
            # process file data
            new_data = func_that_processes_data(data)
            with open(fpath, 'w') as f:
                f.write(new_data)

在我的两个示例中,文件都是作为文本文件打开的。如果您需要处理字节而不是测试/字符串,请使用 mode arguments of 'rb' or 'wb' 打开文件

【讨论】:

  • 谢谢,但我很困惑!你能告诉我“fname_meets_my_criteria”和“new_file_path”是什么吗?
【解决方案3】:

你可以这样使用listdir()

# pathname of root dir
images_path = "./data"

# filtered file extension
suffix = ".png"

# For each image,
for i in os.listdir(images_path):
    file = os.path.basename(i)
    fileName, fileExtension = os.path.splitext(file)
    # is it an image file with 'suffix' extension ?
    if os.path.isfile(images_path+'/'+i) and fileExtension == suffix:
        # do some coding

【讨论】:

  • 感谢您的回答,但它不能以我需要的方式工作。实际上,这段代码并没有进入每个子文件夹,只是循环访问不同的子文件夹。 “如果”的值是 False,因为我在每个子文件夹中都有 .png 文件。
【解决方案4】:

我可以找到我的答案!这很简单,但我在命名时犯了一个错误。所以,下面写的代码可能会帮助其他人遇到同样的问题:

path = "./data/"

for subfolder in os.listdir(path):
    subfolder_name = path + subfolder

    for imgs in os.listdir(subfolder_name):
        imagename = subfolder_name + '/' + imgs

        # do some coding

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-14
    • 2011-08-14
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-21
    • 2011-10-04
    相关资源
    最近更新 更多