同时逐行读取python中的n个文件

时间:2014-04-29 19:34:35

标签: python file statistics

我想要对其进行统计的文件夹中的测量数据CSV文件有一个未知数(可能会随时间变化)。 CSV在所有数据中都有5列数据。我希望能够分别对每条线进行统计分析(多次测量的平均值,stdev等)。 ATM我已经获得了文件夹中的列表文件,将它们存入列表并尝试从列表中打开文件。 尝试迭代文件上的行时,它会变得非常混乱。现在我只是尝试将内容附加到列表并将其输出到其他文件中。没运气。 代码可能不是很干净,我是编程的初学者,但我们走了:

import re
import os

lines_to_skip = 25
workingdir = os.path.dirname(os.path.realpath(__file__))
file_list = []
templine = []
lineNo = 0

print ("Working in %s" %workingdir)
os.chdir(workingdir)
for file in os.listdir(workingdir):
        if file.endswith('.csv'):
                #list only file name without extension (to be able to use filename as variable later)
                file_list.append(file[0:-4])
#open all files in the folder
print (file_list)
for i, value in enumerate(file_list):
    exec "%s = open (file_list[i] + '.csv', 'r')" % (value)

#open output stats file
fileout = open ('zoutput.csv', 'w')

#assuming that all files are of equal length (as they should be)
exec "for x in len(%s + '.csv'):" % (file_list[0])
for i in xrange(lines_to_skip):
        exec "%s.next()" % (file_list[0])
        for j, value in enumerate(file_list):
                templine[:]=[]
                #exec "filename%s=value" % (j)
                exec "line = %s.readline(x)" % (value)
                templine.extend(line)
        fileout.write(templine)

fileout.close()
#close all files in the folder
for i, value in enumerate(file_list):
    #exec "filename%s=value" % (i)
    exec "%s.close()" % (value)

有关我如何以其他方式做到这一点或改进现有方法的任何建议? 前25行只是信息字段,这对我来说是无用的。我可以分别从每个文件中删除前25行(而不是试图跳过它们),但我想它并不重要。 请不要建议使用电子表格或其他统计软件 - 到目前为止,我所尝试过的任何一种软件都没有能够咀嚼我拥有的大量数据。 感谢

1 个答案:

答案 0 :(得分:1)

如果我正确理解你的问题,你想要将每个文件的列粘贴到另一个上,并且从N个文件中,用C列和R行,你想要一次处理一行,其中每行有N * C列?

$ cat rowproc.py
import sys

for l in sys.stdin:
    row = map(float, l.split())
# process row

$ paste *.csv | tail -n+25 | python rowproc.py

或者,如果你不幸的是没有类似Unix的环境,并且必须在python中做所有事情:

import sys
from  itertools import izip

filehandles = [ open(fn) for fn in sys.argv[1:] ]
for i, rows in enumerate(izip(*filehandles)):
    if i<25: continue

    cols = [ map(float, row.split()) for row in rows ]
    print cols

结果:

[[150.0, 26.0], [6.0, 8.0], [14.0, 10.0]]
[[160.0, 27.0], [7.0, 9.0], [16.0, 11.0]]
[[170.0, 28.0], [8.0, 10.0], [18.0, 12.0]
...

只要您能够同时打开足够的文件,这两种方法都可以处理任意大量的数据。

如果您无法通过argv传递文件名,请使用Glob