分类: Python/Ruby
2012-11-26 17:05:24
In [16]: ls a.c* fileslist.py* makefile* os.path.py* pe.pl* printf* pritf.c rok.sh* scanf* shellexit.sh* test* a.out* lish.h me.txt packages.xml* perl.pl* printf.c* reg.c samples/ scanf.c* swap* test.c* In [17]: In [17]: for i in os.walk(os.getcwd()): print i[0] ....: /home/yangfeng/python /home/yangfeng/python/samples /home/yangfeng/python/samples/aa /home/yangfeng/python/samples/aa/bb /home/yangfeng/python/samples/aa/bb/cc In [18]: for i in os.walk(os.getcwd()): print i[1] ....: ['samples'] ['aa'] ['bb'] ['cc'] [] In [19]: for i in os.walk(os.getcwd()): print i[2] ....: ['me.txt', '.test.c.swp', 'pritf.c', 'lish.h', 'printf.c', 'makefile', 'scanf.c', 'a.out', 'printf', 'reg.c', '.swap.c.swp', '.fileslist.py.swp', 'test.c', 'test', 'scanf', 'fileslist.py', 'packages.xml', 'os.path.py', 'shellexit.sh', 'a.c', 'swap', 'pe.pl', 'rok.sh', 'perl.pl'] [] [] [] []
这个方法返回的是一个三元tupple(dirpath, dirnames, filenames),
其中第一个是各个目录路径,
第二个是各个目录路径下的文件夹,
第三个是各个目录路径下的文件.
dirpath是一个string,代表目录的路径,
dirnames是一个list,包含了dirpath下所有子目录的名字,
filenames是一个list,包含了非目录文件的名字.这些名字不包含路径信息,如果需要得到全路径,需要使用 os.path.join(dirpath, name).
下面是可以看到 os.walk 方法返回的内容.
代码:
In [20]: for i in os.walk(os.getcwd()): print i ....: ('/home/yangfeng/python', ['samples'], ['me.txt', '.test.c.swp', 'pritf.c', 'lish.h', 'printf.c', 'makefile', 'scanf.c', 'a.out', 'printf', 'reg.c', '.swap.c.swp', '.fileslist.py.swp', 'test.c', 'test', 'scanf', 'fileslist.py', 'packages.xml', 'os.path.py', 'shellexit.sh', 'a.c', 'swap', 'pe.pl', 'rok.sh', 'perl.pl']) ('/home/yangfeng/python/samples', ['aa'], []) ('/home/yangfeng/python/samples/aa', ['bb'], []) ('/home/yangfeng/python/samples/aa/bb', ['cc'], []) ('/home/yangfeng/python/samples/aa/bb/cc', [], [])