python2.7 获取文件夹下所有文件

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

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

#!/usr/bin/python
# #encoding=utf-8

import os
#最外层文件路径
root_dir = 'C:/Users/v_zhengcaihao/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

猜你喜欢

转载自blog.csdn.net/niliudeyu_z/article/details/81145846