2018-05-22 14:39:56 548浏览
如今想要学习Python的小伙伴越来越多,不论是参加Python培训还是自学Python开发的小伙伴都有。本篇文章给喜欢Python开发的小伙伴分享一下Python中如何遍历一个目录 输出所有的文件名,希望能帮到对Python开发感兴趣的小伙伴们。
python 获取一个文件夹内(包括子文件夹)所有文件的名字和路径
import os dir = "e:\\" for root, dirs, files in os.walk(dir): for file in files: print os.path.join(root,file)
或:
import os path = r'e:\case' fns = [os.path.join(root,fn) for root, dirs, files in os.walk(path) for fn in files] for f in fns: print(f) print(len(fns))
#coding=utf-8 import os def GetFileList(dir, fileList): newDir = dir if os.path.isfile(dir): fileList.append(dir.decode('gbk')) elif os.path.isdir(dir): for s in os.listdir(dir): #如果需要忽略某些文件夹,使用以下代码 #if s == "xxx": #continue newDir=os.path.join(dir,s) GetFileList(newDir, fileList) return fileList list = GetFileList('D:\\workspace\\PyDemo\\fas', []) for e in list: print e
好了,关于Python中如何遍历一个目录及输出所有的文件名就先给大家分享这些,想要学习Python的小伙伴快到扣丁学堂Python在线学习报名学习吧。扣丁学堂不仅有专业的老师和与时俱进的课程体系,还有大量的Python在线视频供学员观看学习,想要学好Python高薪就业的小伙伴快快行动吧。扣丁学堂Python技术交流群:279521237。
【关注微信公众号获取更多学习资料】