我是靠谱客的博主 羞涩香水,这篇文章主要介绍python2.7 获取文件夹下所有文件,现在分享给大家,希望可以做个参考。

最近因为工作中需要写一些简单的Python脚本,然后就查资料学习了一下,在此做个学习笔记。

需求:获取给定文件夹下的所有文件,包括子文件夹中的文件也要获取。直接上代码:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#!/usr/bin/python # #encoding=utf-8 import os #最外层文件路径 root_dir = 'C:/Users/v_c/Desktop/rainbow/ripVideo/neg/' #文件列表,不含文件夹 file_list = [] #获取给定文件夹下所有文件 def getFilesPathAndName(root_dir):   #os.path.isdir(root_dir):用来判断root_dir是不是已经存在的路径,存在返回true,否则false if os.path.isdir(root_dir): for root, dirs, files in os.walk(root_dir):#文件目录遍历 print root, dirs, files for file in files: file_list.append(file)#将文件追加到file_list列表中,方便在其他函数中使用 print(file_list) print(str(len(file_list))) else: print '非法路径,请确认路径的正确性' if __name__ == '__main__': getFilesPathAndName(root_dir) 补充:os.listdir(root_dir):这个方法只能获取给定文件夹中的文件和文件夹的名字,不会进一步去获取子文件夹中的文件。

这位大佬的这篇博客对os.path模块做了详细的介绍,有兴趣的可以看看。

os.path模块详解:https://www.cnblogs.com/wuxie1989/p/5623435.html

最后

以上就是羞涩香水最近收集整理的关于python2.7 获取文件夹下所有文件的全部内容,更多相关python2.7内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(64)

评论列表共有 0 条评论

立即
投稿
返回
顶部