码迷,mamicode.com
首页 > 编程语言 > 详细

python列出一个文件夹及其子目录的所有文件

时间:2016-06-30 11:05:09      阅读:269      评论:0      收藏:0      [点我收藏+]

标签:python   os.path   os.walk   遍历   

>>> import os
>>> for i in os.walk("."):
...     print i[0],"\n##",i[1],"\n##",i[2]
... 
.                             #当前目录
## [‘fa‘, ‘out‘]              #当前目录中的子目录      
## [‘meta_rna.sh‘, ‘nohup.out‘, ‘log.cpu‘, ‘blast_seq.py‘]
./fa                         # 第一个子目录
## []                        # 第一个子目录中的目录
## [‘assemblyar_new_2.faa‘]
./out                        # 第二个子目录
## []                        # 第二个子目录中的目录
## [‘assemblyar_new_2.faa.coord‘, ‘assemblyar_new_2.faa.mask‘, ‘assemblyar_new_2.faa.seq‘, ‘result_1.xm‘, ‘result.xml‘, ‘blast_seq.py‘]


也可以用 os.path.walk, 先定义一个访问文件夹的函数, VisitDir

>>> def VisitDir(arg, dirname, names):
...     for filespath in names:
...         print os.path.join(dirname, filespath)
... 



>>> path="."
>>> os.path.walk(path, VisitDir, ())
./meta_rna.sh
./fa
./out
./nohup.out
./log.cpu
./blast_seq.py
./fa/assemblyar_new_2.faa
./out/assemblyar_new_2.faa.coord
./out/assemblyar_new_2.faa.mask
./out/assemblyar_new_2.faa.seq
./out/result_1.xm
./out/result.xml
./out/blast_seq.py

>>> os.getcwd()
‘/home/served_pro/Find_nick‘
>>> abs_path= os.getcwd()
>>> os.path.walk(abs_path, VisitDir, ())
/home/served_pro/Find_nick/meta_rna.sh
/home/served_pro/Find_nick/fa
/home/served_pro/Find_nick/out
/home/served_pro/Find_nick/nohup.out
/home/served_pro/Find_nick/log.cpu
/home/served_pro/Find_nick/blast_seq.py
/home/served_pro/Find_nick/fa/assemblyar_new_2.faa
/home/served_pro/Find_nick/out/assemblyar_new_2.faa.coord
/home/served_pro/Find_nick/out/assemblyar_new_2.faa.mask
/home/served_pro/Find_nick/out/assemblyar_new_2.faa.seq
/home/served_pro/Find_nick/out/result_1.xm
/home/served_pro/Find_nick/out/result.xml
/home/served_pro/Find_nick/out/blast_seq.py


python列出一个文件夹及其子目录的所有文件

标签:python   os.path   os.walk   遍历   

原文地址:http://matrix6ro.blog.51cto.com/1746429/1794435

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!