遍历文件夹,Python中的文件的几个子文件夹
问题描述:
我有一个类似于下面概述的文件夹结构。遍历文件夹,Python中的文件的几个子文件夹
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
我看了网上,看到在os.walk for循环,类似于第一FILEA和第一FILEB:
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
但是,这似乎只适用于如果有一个文件直接在一个子目录。我的问题是,有时子目录内有一个额外的子目录(!!)
有没有人有任何想法如何解决这个问题?
答
您的问题实际上是这两行,删除它们,你前人的精力被罚款:
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
因此,我们清楚地看到,由于“坏行”,第一行的两个子文件夹test10
和test22
已被完全忽略。
你说过我在网上看过,在for循环中看到os.walk,类似于'。那么你是说你在问题中输入的代码不是你运行的代码? –
不,我已经使用这段代码,并修改了其他代码也没有工作 –