os.walk的用法

用法:

1
walk( top [, topdown=True [, onerror=None]] )( top [, topdown=True [, onerror=None]] )

这个函数可以遍历一个目录树,产生一系列包含3个元素(路径、目录名、文件名)的元组。其中路径是一个字符串。目录名是一个包含所有子目录的列表 (但 . 和 .. 除外)。文件名则是包含该目录下所有文件名的一个列表,需要注意的是,文件名并不包含路径。如果想得到文件的完整路径,可以使用

1
os.path.join( dirpath, name ).path.join( dirpath, name )

可选项参数 topdown 如果不指定,则默认为 true,这时产生结果的顺序是先列出根目录,再列出子目录。实际测试一下:

1
2
3
4
5
6
7
8
9
10
11
>>> import os
>>> a = os.walk( '.' )
>>> a
<generator object at 0x00935698>
>>> for dirpath, dirnames, filenames in a:
...     print dirpath, dirnames, filenames
...
. ['2'] ['1.txt']
./2 ['3'] ['2.txt']
./2/3 [] ['3.txt']
>>>import os
>>> a = os.walk( '.' )
>>> a
<generator object at 0x00935698>
>>> for dirpath, dirnames, filenames in a:
...     print dirpath, dirnames, filenames
...
. ['2'] ['1.txt']
./2 ['3'] ['2.txt']
./2/3 [] ['3.txt']
>>>

反之,如果 topdown 可选项等于 False,则结果产生的顺序与上述相反:

1
2
3
4
5
6
7
8
9
10
11
>>> import os
>>> a = os.walk( '.' )
>>> a
<generator object at 0x00935698>
>>> for dirpath, dirnames, filenames in a:
...     print dirpath, dirnames, filenames
...
. ['2'] ['1.txt']
./2 ['3'] ['2.txt']
./2/3 [] ['3.txt']
>>>import os
>>> a = os.walk( '.' )
>>> a
<generator object at 0x00935698>
>>> for dirpath, dirnames, filenames in a:
...     print dirpath, dirnames, filenames
...
. ['2'] ['1.txt']
./2 ['3'] ['2.txt']
./2/3 [] ['3.txt']
>>>

猜你喜欢

转载自blog.csdn.net/stonethree0230/article/details/3110409