os.walk 递归地遍历每个文件夹,返回 generator
for i, (root, dirs, files) in enumerate(os.walk('example')):
print i
print 'root:', root
print 'subdirs:', dirs
print 'files:', files
print
0
root: example
subdirs: ['labelTxt', 'images']
files: []
1
root: example/labelTxt
subdirs: []
files: ['P1234.txt', 'P1888.txt', 'P0706.txt', 'P0770.txt', 'P1088.txt', 'P2598.txt', 'P2709.txt']
2
root: example/images
subdirs: []
files: ['P1888.png', 'P0706.png', 'P0770.png', 'P1088.png', 'P2709.png', 'P2598.png', 'P1234.png']
example 路径:
example
├── images
│ ├── P0706.png
│ ├── P0770.png
│ ├── P1088.png
│ ├── P1234.png
│ ├── P1888.png
│ ├── P2598.png
│ └── P2709.png
└── labelTxt
├── P0706.txt
├── P0770.txt
├── P1088.txt
├── P1234.txt
├── P1888.txt
├── P2598.txt
└── P2709.txt
2 directories, 14 files
GetFileFromThisRootDir 获取 Root 下的所有 files path
def GetFileFromThisRootDir(dir, ext=None):
allfiles = []
needExtFilter = (ext != None)
# os.walk() generate (root, dirs, files)
# root: root dir (string)
# dirs: root subdirs (list)
# files: root files (list)
for root, dirs, files in os.walk(dir):
for filespath in files:
filepath = os.path.join(root, filespath) # root 已变成 files 的上一级目录了
extension = os.path.splitext(filepath)[1][1:]
if needExtFilter and extension in ext: # limit exts, such as [.png, .jpg]
allfiles.append(filepath)
elif not needExtFilter:
allfiles.append(filepath)
return allfiles
if __name__ == '__main__':
for file_path in GetFileFromThisRootDir('example'):
print file_path
example/labelTxt/P1234.txt
example/labelTxt/P1888.txt
example/labelTxt/P0706.txt
example/labelTxt/P0770.txt
example/labelTxt/P1088.txt
example/labelTxt/P2598.txt
example/labelTxt/P2709.txt
example/images/P1888.png
example/images/P0706.png
example/images/P0770.png
example/images/P1088.png
example/images/P2709.png
example/images/P2598.png
example/images/P1234.png
网友评论