是否可以在python中一次处理多个txt文件?

时间:2020-04-30 01:13:28

标签: python numpy data-analysis

我有1080个.txt文件,每个文件在三列中包含超过10万行的值。我必须对每个.txt文件中的第一列进行平均。

任何执行循环的方法都被证明太慢,因为一次numpy.loadtxt只能加载一个文件。

更重要的是,我有38个文件夹需要在其中执行此操作。总共38 * 1030个文件。使用time模块获取每个numpy.loadtxt的计算时间大约为1.7秒。因此,要在所有文件夹上运行的总时间超过21个小时,这似乎有点太多时间。

所以这让我想知道是否有一种方法可以通过打开多个txt文件并在第一列进行平均来一次执行多个操作。然后,由于顺序很重要,因此还可以按照txt文件的相应顺序存储该平均值。

由于我是初学者,所以我不确定这是否是最快的方法。预先感谢。


    import numpy as np
    import glob
    import os

    i = 0 
    while i < 39:

        source_directory = "something/" + str(i)    #Go to specific folder with the numbering

        hw_array = sorted(glob.glob(source_directory + "/data_*.txt"))  # read paths of 1080 txt files

        velocity_array = np.zeros((30,36,3))

        for probe in hw_array:

            x = 35 - int((i-0.0001)/30)         #describing position of the probes where velocities are measured
            y = (30 - int(round((i)%30)))%30

            velocity_column = np.loadtxt(data_file, usecols=(0))    #step that takes most time
            average_array = np.mean(velocity_column, axis=0)

            velocity_array[y,x,0] = average_array
            velocity_array[y,x,1] = y*(2/29)
            velocity_array[y,x,2] = x*0.5

        np.save(r"C:/Users/md101/Desktop/AE2/Project2/raw/" + "R29" + "/data" + "R29", velocity_array) #save velocity array for use in later analysis
        i += 1

2 个答案:

答案 0 :(得分:0)

Python的I / O速度很慢,您的大部分时间都花在了与操作系统的对话以及与打开文件相关的其他费用上。

Python中的线程很奇怪,并且仅在某些情况下提供了改进。这就是为什么它对您的情况有益。在Python中,线程的工作方式是,如果线程具有许可权(称为获取GIL或全局解释器锁,请阅读该内容),它将做一些事情。当它等待诸如I / O之类的东西时,它将通过GIL传递到另一个线程。这将允许您的文件在具有GIL的情况下进行操作(平均第一行),并且在打开文件时会将GIL传递给另一个文件以执行操作

答案 1 :(得分:0)

完全有可能编写一个函数来从目录中加载文件,并生成一个multiprocessing并以将近三分之一的时间完成它。或者,不要按目录并行化,而要按文件并行处理工作并从该工作队列中读取。

一些伪代码:

pool = multiprocessing.Pool()

workers = []
for d in os.listdir("."):
  for f in os.listdir(d):
    workers.append(pool.apply_async(counter_function_for_file, (os.path.join(d, f),))

s = sum(worker.get() for worker in workers)

...,然后将要从文件中读取的代码放在该counter_function_for_file(filename)函数中。