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

python简介

Python是一种解释型、面向对象、动态数据类型的高级程序设计语言。

Python由Guido van Rossum于1989年底发明,第一个公开发行版发行于1991年。

像Perl语言一样, Python 源代码同样遵循 GPL(GNU General Public License)协议。

立即学习“Python免费学习笔记(深入)”;

>>> import os>>> for i in os.walk("."):... print i[0],"##",i[1],"##",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']

登录后复制

立即学习“Python免费学习笔记(深入)”;

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

立即学习“Python免费学习笔记(深入)”;

>>> 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列出文件夹下的所有文件

立即学习“Python免费学习笔记(深入)”;

#方法1:使用os.listdirimport osfor filename in os.listdir(r'c:\windows'):print filename#方法2:使用glob模块,可以设置文件过滤import globfor filename in glob.glob(r'c:\windows\*.exe'):print filename#方法3:通过os.path.walk递归遍历,可以访问子文件夹import os.pathdef processDirectory ( args, dirname, filenames ):print 'Directory',dirnamefor filename in filenames:print ' File',filenameos.path.walk(r'c:\windows', processDirectory, None )#方法4:非递归import osfor dirpath, dirnames, filenames in os.walk('c:\\winnt'):print 'Directory', dirpathfor filename in filenames:print ' File', filename

登录后复制

立即学习“Python免费学习笔记(深入)”;

另外,判断文件与目录是否存在:

立即学习“Python免费学习笔记(深入)”;

import osos.path.isfile('test.txt') #如果不存在就返回Falseos.path.exists(directory) #如果目录不存在就返回False

登录后复制

立即学习“Python免费学习笔记(深入)”;

以上所述是小编给大家介绍的Python列出一个文件夹及其子目录的所有文件,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对PHP中文网的支持!

更多Python列出一个文件夹及其子目录的所有文件相关文章请关注PHP中文网!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2278499.html

(0)
上一篇 2025年2月27日 16:49:40
下一篇 2025年2月26日 00:49:48

AD推荐 黄金广告位招租... 更多推荐

发表回复

登录后才能评论