python-3.x - 动态创建文件夹并将 csv 文件写入该文件夹

标签 python-3.x dataframe glob writefile create-directory

我想从一个文件夹中读取几个输入文件,执行一些转换,动态创建文件夹并将 csv 写入相应的文件夹。这里的重点是我有输入路径,就像

"Input files\P1_set1\Set1_Folder_1_File_1_Hour09.csv" - for a single patient (This file contains readings of patient (P1) at 9th hour)


同样,每个患者有多个文件,每个患者文件分组在每个文件夹下,如下所示
enter image description here
因此,要读取每个文件,我在代码中使用通配符正则表达式,如下所示
我已经尝试使用 glob 包并且能够成功读取它,但是在创建输出文件夹和保存文件时遇到了问题。我正在解析文件字符串,如下所示

f = "Input files\P1_set1\Set1_Folder_1_File_1_Hour09.csv"

f[12:] = "P1_set1\Set1_Folder_1_File_1_Hour09.csv"

filenames = sorted(glob.glob('Input files\P*_set1\*.csv'))
for f in filenames:
   print(f)     #This will print the full path
   print(f[12:]) # This print the folder structure along with filename
   df_transform = pd.read_csv(f)
   df_transform = df_transform.drop(['Format 10','Time','Hour'],axis=1)
   df_transform.to_csv("Output\" + str(f[12:]),index=False)
我希望输出文件夹包含每个患者在各自文件夹下分组的 csv 文件。下面的屏幕截图显示了如何在输出文件夹中排列转换后的文件(与输入文件夹的结构相同)。请注意“Output”文件夹已经存在(创建一个你知道的文件夹很容易)
enter image description here

最佳答案

所以要读取文件夹中的文件使用 os library 然后你可以做

import os
folder_path = "path_to_your_folder"
dir = os.listdir(folder_path)
for x in dir:
    df_transform = pd.read_csv(f)
    df_transform = df_transform.drop(['Format 10','Time','Hour'],axis=1)
    if os.path.isdir("/home/el"):
        df_transform.to_csv("Output/" + str(f[12:]),index=False)
    else:
        os.makedirs(folder_path+"/")
        df_transform.to_csv("Output/" + str(f[12:]),index=False)    

现在代替用户 f[12:] 在 for 循环中拆分 x
file_name = x.split('/')[-1] #if you want filename.csv

让我知道这是否是你想要的

关于python-3.x - 动态创建文件夹并将 csv 文件写入该文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55507926/

相关文章:

python-3.x - 在 BlockingIOError : write could not complete without blocking 上记录阻塞

python-3.x - 基于不变式/散列的拆分/分区列表?

Python 3 : Insertion Sort comparisons counter

python - 检查列表是否与元组完全相同

python - 从 pandas DataFrame 返回最后一个有效(非空)值

python - 数据帧结构操作

javascript - 如何向传递给 gulp.src 的 glob 添加路径前缀?

node.js - npm 安装失败,错误代码为 "Cannot find module ' glob'"

r - 绑定(bind)具有不同行数的列

rust - 从 glob-entry 获取文件路径以用于 fs::read_to_string