python 目录遍历 目录文件列表 介绍

目录

一、使用os.walk遍历所有的目录和文件

二、利用os.listdir递归获取所有的目录路径和文件路径


目录结构如下图:

test---a------d------g--------g.txt

test---a------d------a.txt

test---a------e

--------b

--------c

--------1.txt

--------2.txt

一、使用os.walk遍历所有的目录和文件

1、获取test目录下的所有文件

for root,dirs,files in os.walk(r"D:\test"):
	for file in files:
	    #获取文件所属目录
	    print(root)
	    #获取文件路径
	    print(os.path.join(root,file))

2、获取test目录下的所有目录

for root,files in os.walk(r"D:\test"):
	for dir in dirs:
	    #获取目录的名称
	    print(dir)
	    #获取目录的路径
	    print(os.path.join(root,dir))

二、利用os.listdir递归获取所有的目录路径文件路径

def get_file_path(root_path,file_list,dir_list):
    #获取该目录下所有的文件名称和目录名称
    dir_or_files = os.listdir(root_path)
    for dir_file in dir_or_files:
        #获取目录或者文件的路径
        dir_file_path = os.path.join(root_path,dir_file)
        #判断该路径为文件还是路径
        if os.path.isdir(dir_file_path):
            dir_list.append(dir_file_path)
            #递归获取所有文件和目录的路径
            get_file_path(dir_file_path,dir_list)
        else:
            file_list.append(dir_file_path)
 
if __name__ == "__main__":
    #根目录路径
    root_path = r"D:\test"
    #用来存放所有的文件路径
    file_list = []
    #用来存放所有的目录路径
    dir_list = []
    get_file_path(root_path,dir_list)
    print(file_list)
    print(dir_list)

 

 

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...