python 递归获取文件夹目录,获取文件夹下文件。存储到本地txt文件中。

os.chdir() 方法用于改变当前工作目录到指定的路径。

os.path.abspath()返回文件的绝对路径

os.curdir直接使用时会返回‘.’(这个表示当前路径)

os.listdir() 方法用于返回指定的文件夹包含的文件或文件夹的名字的列表

import os
file_dir=[]
def check_file(file_path):
    os.chdir(file_path)
    one_dir=os.path.abspath(os.curdir)
    file_dir.append(one_dir)
    all_file = os.listdir()
    files = []
    for f in all_file:
        if os.path.isdir(f):
            files.extend(check_file(file_path+'/'+f))
            os.chdir(file_path)
        else:
            files.append(f)
    return file_dir

file_list = check_file("文件路径")
print(file_list)
with open("./输入文件名.txt","w") as f:
    for data in file_list:
        f.write(data+"\n")

猜你喜欢

转载自www.cnblogs.com/qxh-beijing2016/p/12465650.html