首页 > 解决方案 > 使用可变路径读取项目文件夹中的所有文件 - Python

问题描述

寻找有关如何读取项目文件夹中所有 csv 文件的想法。

例如,以下代码是我当前工作代码的一部分,我的“ProjectFolder”在桌面上,我正在硬编码路径。在项目文件夹中,我有“csvfolder”,其中有我所有的 csv 文件

但是,如果我将“ProjectFolder”移动到不同的硬盘驱动器或其他位置,我的路径将失败,我必须提供新路径。有没有一种聪明的方法可以不用担心项目文件夹的位置?

path = r'C:\Users\XXX\Desktop\ProjectFolder\csvFolder' # use your path
all_files = glob.glob(path + "/*.csv")

df_mm = pd.concat((pd.read_csv(f, usecols=["[mm]"]) for f in all_files),
               axis = 1, ignore_index = True)

标签: pythonoperating-systemglob

解决方案


我们有动态和绝对路径的概念,只要在谷歌上搜索“绝对路径 vs 相对路径”;在你的情况下,如果你的 python 文件在 ProjectFolder 中,你可以简单地试试这个:

from os import listdir
from os.path import dirname, realpath, join


def main():
    # This is your project directory
    current_directory_path = dirname(realpath(__file__))
    # This is your csv directory
    csv_files_directory_path = join(current_directory_path, "csvFolder")
    
    for each_file_name in listdir(csv_files_directory_path):
        if each_file_name.endswith(".csv"):
            each_csv_file_full_path = join(csv_files_directory_path, each_file_name)
            
            # Do whatever you want with each_csv_file_full_path


if __name__ == '__main__':
    main()

推荐阅读