【问题标题】:Loop of a function for several files多个文件的函数循环
【发布时间】:2020-02-12 14:11:47
【问题描述】:

我是python新手,想知道下期的方法。

我有一个 python 脚本,它从实验中收集数据并将它们保存为按列组织的 .csv 格式。

利用下面的函数,我可以每天创建一个文件夹(DATE-folder)来执行实验,每次运行脚本时创建一个子文件夹(Run_(j)),在其中收集 5 个文件子文件夹。

DATE      = datetime.now().strftime("%Y-%m-%d")

if not os.path.isdir(os.path.join(os.getcwd(), DATE)):
    os.makedirs(DATE)

def move_files():
    os.chdir(DATE)
    for j in range(1, 101):
        if not os.path.exists(os.path.join(os.getcwd(), 'Run_'+ str(j))):
            break
    os.makedirs('Run_' + str(j))
    src_files = os.listdir(os.curdir)
    for file_name in src_files:
        full_file_name = os.path.join(os.curdir, file_name)
        if os.path.isfile(full_file_name):
            shutil.move(full_file_name, 'Run_' + str(j))

作为一个例子,我得到了类似的东西:

DATE/ Run_1 / File_sweep_1.csv,File_sweep_2.csv,File_sweep_3.csv,File_sweep_4.csv,File_sweep_5.csv
      Run_2 / File_sweep_1.csv,File_sweep_2.csv,File_sweep_3.csv,File_sweep_4.csv,File_sweep_5.csv
        .
        .
      Run_j / File_sweep_1.csv,File_sweep_2.csv,File_sweep_3.csv,File_sweep_4.csv,File_sweep_5.csv

现在,我想使用另一个脚本来分析实验中的数据,避免更改文件所在目录的路径,假设以某种方式像循环一样执行它们。直到我使用这个的那一刻:

os.chdir('MainPath/2020-02-12/Run_1')
print('You are working on this directory:\n', os.getcwd(), '\n')
print('The files in the directory are:\n',os.listdir(), '\n')

data = pd.read_csv("File_sweep_1.csv") 

然后我应用我的函数并得到我的结果,但是我想避免手动更改 File_sweep_1.csv、File_sweep_2.csv... File_sweep_5.csv。

基本上我想要的是运行我的分析函数,并将它应用于 DATE 文件夹内每个子文件夹 Run_(j) 中的每个文件。 DATE 文件夹并不麻烦,因为我可以在需要时手动更改它。

您对如何进行有任何提示?

【问题讨论】:

    标签: python python-3.x directory


    【解决方案1】:

    我认为这是将所有文件加载到特定文件夹中的有效方法

    import os 
    
    def load_data():
        folder = 'MainPath/2020-02-12/Run_1'
        for root, _, files in os.walk(folder):
            for file in files:
                if file.endswith(".csv"):
                    yield pd.read_csv(root + os.path.sep + file)
    
    for data in load_data():
        # do something with the data
    
    

    python 方法 walk() 通过自上而下遍历树来生成目录树中的文件名

    【讨论】:

    • 感谢您的回答。按照这些步骤,我可以看到每个目录中的文件。但是,如何从那里导入数据以使用我的功能?利用产量不允许我做类似的事情:产量data = pd.read_csv(root + os.path.sep + file)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 2014-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多