Python获取指定路径下所有文件的绝对路径

需求

给出制定目录(路径),获取该目录下所有文件的绝对路径:

实现

方式一:

import os


def get_file_path_by_name(file_dir):
    '''
    获取指定路径下所有文件的绝对路径
    :param file_dir:
    :return:
    '''
    L = []
    for root, dirs, files in os.walk(file_dir):  # 获取所有文件
        for file in files:  # 遍历所有文件名
            if os.path.splitext(file)[1] == '.csv':  
                L.append(os.path.join(root, file))  # 拼接处绝对路径并放入列表
    print('总文件数目:', len(L))
    return L


print(get_file_path_by_name('D:\stock_data'))

方式二:

import os

l = []


def listdir(path, list_name):  # 传入存储的list
    for file in os.listdir(path):
        file_path = os.path.join(path, file)
        if os.path.isdir(file_path):
            listdir(file_path, list_name)
        else:
            list_name.append(file_path)
    return l


print(listdir('D:\stock_data', l))

结果

 

 关键字:os.walk()

猜你喜欢

转载自www.cnblogs.com/bigtreei/p/9316426.html