Python读取文件目录树——os.walk

作者:襄阳西继迅达电梯有限公司  发布时间:2017-09-07 13:29:35
Python读取文件目录树——os.walk

os.walk是Python的内置函数用来遍历文件目录树。
[python]
import os

rootDir = 'd:\\assa'
for dirName, subdirList, fileList in os.walk(rootDir):
print('Folder: %s' % dirName)
for fname in fileList:
print('\t%s' % fname)

import os

rootDir = 'd:\\assa'
for dirName, subdirList, fileList in os.walk(rootDir):
print('Folder: %s' % dirName)
for fname in fileList:
print('\t%s' % fname)目录结构为:

[python]
+test
+f1
2.txt
+f2
3.txt
1.txt

+test
+f1
2.txt
+f2
3.txt
1.txt输出结果为:
[python]
Folder: d:\Python Code\test
1.txt
Folder: d:\Python Code\test\f1
2.txt
Folder: d:\Python Code\test\f2
3.txt

Folder: d:\Python Code\test
1.txt
Folder: d:\Python Code\test\f1
2.txt
Folder: d:\Python Code\test\f2
3.txt可以看到这是自顶向下的遍历顺序,如果我们要自底向上,可视化专题,先从最深处的文件开始遍历,专题,可以加上topdown参数:[python] view plaincopyprint?import os

rootDir = 'd:\\Python Code\\test'
for dirName, subdirList, fileList in os.walk(rootDir, topdown = False):
print('Folder: %s' % dirName)
for fname in fileList:
print('\t%s' % fname)

import os

rootDir = 'd:\\Python Code\\test'
for dirName, subdirList, fileList in os.walk(rootDir, topdown = False):
print('Folder: %s' % dirName)
for fname in fileList:
print('\t%s' % fname)结果:
[python]
Folder: d:\Python Code\test\f1
2.txt
Folder: d:\Python Code\test\f2
3.txt
Folder: d:\Python Code\test
1.txt

Folder: d:\Python Code\test\f1
2.txt
Folder: d:\Python Code\test\f2
3.txt
Folder: d:\Python Code\test
1.txt如果想要在搜索的时候加上条件?比如跳过第一个文件夹,os.walk也可以做到:[python] view plaincopyprint?import os

rootDir = 'd:\\Python Code\\test'
for dirName, subdirList, fileList in os.walk(rootDir):
print('Folder: %s' % dirName)
for fname in fileList:
print('\t%s' % fname)
if len(subdirList) > 0:
del subdirList[0]

import os

rootDir = 'd:\\Python Code\\test'
for dirName, subdirList, fileList in os.walk(rootDir):
print('Folder: %s' % dirName)
for fname in fileList:
print('\t%s' % fname)
if len(subdirList) > 0:
del subdirList[0]结果:
[python]
Folder: d:\Python Code\test
1.txt
Folder: d:\Python Code\test\f2
3.txt

Folder: d:\Python Code\test
1.txt
Folder: d:\Python Code\test\f2
3.txt有的同学却不能得到正确的结果,我们可以看看如下代码:
[python]
import os

rootDir = 'd:\\Python Code\\test'
for dirName, subdirList, fileList in os.walk(rootDir):
print('Folder: %s' % dirName)
for fname in fileList:
print('\t%s' % fname)
if len(subdirList) > 0:
subdirList = subdirList[1:]

import os

rootDir = 'd:\\Python Code\\test'
for dirName, subdirList, fileList in os.walk(rootDir):
print('Folder: %s' % dirName)
for fname in fileList:
print('\t%s' % fname)
if len(subdirList) > 0:
subdirList = subdirList[1:]
结果:

[python]
Folder: d:\Python Code\test
1.txt
Folder: d:\Python Code\test\f1
2.txt
Folder: d:\Python Code\test\f2
3.txt

Folder: d:\Python Code\test
1.txt
Folder: d:\Python Code\test\f1
2.txt
Folder: d:\Python Code\test\f2
3.txt

企业建站2800元起,携手武汉肥猫科技,做一个有见地的颜值派!更多优惠请戳:天门网站建设 http://tianmen.45qun.com

  • 上一篇:2013年10月TIOBE编程语言排行榜,Groovy首次进入Top20
  • 下一篇:最后一页
  •