【问题标题】:Looping through multiple CSV-files in different folders and producing multiple outputs and put these in the same folder based on input循环遍历不同文件夹中的多个 CSV 文件并生成多个输出,然后根据输入将它们放在同一个文件夹中
【发布时间】:2020-02-25 03:55:43
【问题描述】:

问题:我在 1 个主文件夹中有大约 100 个文件夹,每个文件夹都有一个名称和结构完全相同的 csv 文件,例如 input.csv。我为其中一个文件编写了一个 Python 脚本,该脚本将 csv 文件作为输入,并在同一文件夹中提供两个图像作为输出。我想生成这些图像并将它们放在每个文件夹中给定每个文件夹的输入。

有没有快速的方法来做到这一点?到目前为止,我每次都在每个文件夹中复制我的脚本并一直在执行它。对于 5 个文件夹来说没问题,但是对于 100 个文件夹,这将变得乏味并且需要很多时间。

有人可以帮忙吗?我对 w.r.t 编码很陌生。目录、路径、文件等。我已经尝试寻找解决方案,但到目前为止还没有成功。

【问题讨论】:

  • 使用pathlibrglob

标签: python loops directory


【解决方案1】:

你可以试试这样的:

import os
import pandas as pd
path = r'path\to\folders'
filename = 'input'

# get all directories within the top level directory 
dirs = [os.path.join(path, val) for val in os.listdir(path) if os.path.isdir(os.path.join(path, val))]

# loop through each directory 
for dd in dirs:
    file_ = [f for f in os.listdir(dd) if f.endwith('.csv') and 'input' in f]
    if file_:
        # this assumes only a single file of 'filename' and extension .csv exists in each directory 
        file_ = file_[0]
    else:
        continue
    data = pd.read_csv(file_)

    # apply your script here and save images back to folder dd

【讨论】:

    猜你喜欢
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多