【问题标题】:traversing folders, several subfolders for the files in python遍历文件夹,python中文件的几个子文件夹
【发布时间】:2017-02-08 10:01:09
【问题描述】:

我的文件夹结构类似于下面概述的内容。

Path
|
|
+----SubDir1
|       |
|       +---SubDir1A
|       |       |
|       |       |----- FileA.0001.ext
|       |       |----- ...
|       |       |----- ...
|       |       |----- FileA.1001.ext
|       |       |----- FileB.0001.ext
|       |       |----- ...
|       |       |----- ...
|       |       |----- FileB.1001.ext
|       +---SubDir1B
        |
|       |       |----- FileA.0001.ext
|       |       |----- ...
|       |       |----- ...
|       |       |----- FileA.1001.ext
|       |       |----- FileB.0001.ext
|       |       |----- ...
|       |       |----- ...
|       |       |----- FileB.1001.ext
+----SubDir2
|       |
|       |----- FileA.0001.ext
|       |----- ...
|       |----- ...
|       |----- FileA.1001.ext
|       |----- FileB.0001.ext
|       |----- ...
|       |----- ...
|       |----- FileB.1001.ext

我希望能够列出每个 SubDir1 和 SubDir2 的第一个 FileA 和第一个 FileB

我上网查了一下,看到os.walk在for循环中,类似于:

import os

rootDir = '.'
for dirName, subdirList, fileList in os.walk(rootDir):
    print('Found directory: %s' % dirName)
    for fname in fileList:
        print('\t%s' % fname)
    # Remove the first entry in the list of sub-directories
    # if there are any sub-directories present
    if len(subdirList) > 0:
        del subdirList[0

但这似乎只有在子目录中直接有文件时才有效。我的问题是,有时子目录内还有一个额外的子目录(!!)

有人知道如何解决这个问题吗?

【问题讨论】:

  • 你说I've looked online and seen os.walk in a for loop, similar to。那么你的意思是你在问题中输入的代码不是你运行的代码吗?
  • 没有。我已经使用了这段代码并修改了其他也不起作用的代码

标签: python glob directory subdirectory os.walk


【解决方案1】:

您的问题实际上是这两行,删除它们就可以了:

if len(subdirList) > 0:
    del subdirList[0]

解释

他们所做的是他们使每个目录中的第一个子目录在os.walk 有时间走之前消失。因此,您在子目录方面出现奇怪的行为也就不足为奇了。

这是使用以下树对该行为的说明:

test0/
├── test10
│   ├── test20
│   │   └── testA
│   ├── test21
│   │   └── testA
│   └── testA
├── test11
│   ├── test22
│   │   └── testA
│   ├── test23
│   │   └── testA
│   └── testA
└── testA

没有有问题的行:

Found directory: ./test/test0
    testA
Found directory: ./test/test0/test10
    testA
Found directory: ./test/test0/test10/test21
    testA
Found directory: ./test/test0/test10/test20
    testA
Found directory: ./test/test0/test11
    testA
Found directory: ./test/test0/test11/test22
    testA
Found directory: ./test/test0/test11/test23
    testA

有问题的行:

Found directory: ./test/test0
    testA
Found directory: ./test/test0/test11
    testA
Found directory: ./test/test0/test11/test23
    testA

所以我们清楚地看到,由于“坏行”,排在第一位的两个子文件夹 test10test22 已被完全忽略。

【讨论】:

    猜你喜欢
    • 2014-09-28
    • 2023-01-20
    • 2018-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-22
    相关资源
    最近更新 更多