zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python递归文件夹遍历所有文件夹及文件

Python文件遍历递归 所有 文件夹
2023-09-11 14:14:47 时间

第一种 :

#!/usr/bin/env python
# --*-- coding:UTF-8 --*--

import os


def file_name(file_dir):
    for home, dirs, files in os.walk(file_dir):
        print("#######dir list#######")
        for dir in dirs:
            print(dir)
        print("#######dir list#######")

        print("#######file list#######")
        for filename in files:
            print(filename)
            fullname = os.path.join(home, filename)
            print("111", fullname)
        print("#######file list#######")
 
file_name('/opt/HoneypotServers_2019/web_template/1/www')

 

第二种:

#!/usr/bin/env python
# --*-- coding:UTF-8 --*--


import os


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,file_list,dir_list)
        else:
            file_list.append(dir_file_path)
 
if __name__ == "__main__":
    #根目录路径
    root_path = "/opt/HoneypotServers_2019/web_template/1/www"
    #用来存放所有的文件路径
    file_list = []
    #用来存放所有的目录路径
    dir_list = []
    get_file_path(root_path,file_list,dir_list)
    print(file_list)
    print(dir_list)