Python-将多个文件导入单个.csv文件

时间:2012-04-23 01:06:20

标签: python file import

我有125个数据文件,包含两列和21行数据,我想将它们导入一个.csv文件(125对列,只有21行)。 这就是我的数据文件:

enter image description here

我是python的新手,但我想出了以下代码:

import glob
Results = glob.glob('./*.data')
fout='c:/Results/res.csv'
fout=open ("res.csv", 'w')
 for file in Results:
 g = open( file, "r" )
 fout.write(g.read())
 g.close() 
fout.close()

上述代码的问题是所有数据都只复制到两列,每行125 * 21行。

非常感谢任何帮助!

3 个答案:

答案 0 :(得分:1)

这应该有效:

import glob

files = [open(f) for f in glob.glob('./*.data')] #Make list of open files
fout = open("res.csv", 'w')

for row in range(21):
    for f in files:
        fout.write( f.readline().strip() ) # strip removes trailing newline
        fout.write(',')
    fout.write('\n')

fout.close()

请注意,如果您尝试大量文件,此方法可能会失败,我相信Python中的默认限制为256.

答案 1 :(得分:1)

您可能想要尝试python CSV模块(http://docs.python.org/library/csv.html),它提供了非常有用的方法来读取和写入CSV文件。既然你说你只想要21行250列数据,我建议创建21个python列表作为你的行,然后在循环浏览文件时将数据附加到每一行。

类似的东西:

import csv

rows = []
for i in range(0,21):
    row  = []
    rows.append(row)

#not sure the structure of your input files or how they are delimited, but for each one, as you have it open and iterate through the rows, you would want to append the values in each row to the end of the corresponding list contained within the rows list.

#then, write each row to the new csv:

writer = csv.writer(open('output.csv', 'wb'), delimiter=',')
for row in rows:
    writer.writerow(row)

答案 2 :(得分:1)

(抱歉,我无法添加评论。)

[稍后编辑,以下声明错误!!!] “davesnitty生成行循环可以替换为rows = [[]] * 21。”它是错误,因为这会创建空列表列表,但空列表将是外部列表的所有元素共享的单个空列表。

我使用标准csv模块的+1。但是文件应该总是关闭 - 特别是当你打开那么多文件时。还有一个错误。通过 - 从文件中读取的行 - 即使您只在此处写入结果。实际上缺少解决方案。基本上,从文件中读取的行应附加到与行号相关的子列表中。行号应该通过enumerate(reader)获得,其中reader是csv.reader(fin,...)。

[稍后添加] 请尝试以下代码,修复puprose的路径:

import csv
import glob
import os

datapath = './data'
resultpath = './result'
if not os.path.isdir(resultpath):
   os.makedirs(resultpath)

# Initialize the empty rows. It does not check how many rows are
# in the file.
rows = []

# Read data from the files to the above matrix.
for fname in glob.glob(os.path.join(datapath, '*.data')):
    with open(fname, 'rb') as f:
        reader = csv.reader(f)
        for n, row in enumerate(reader):
            if len(rows) < n+1:
                rows.append([])  # add another row
            rows[n].extend(row)  # append the elements from the file

# Write the data from memory to the result file.
fname = os.path.join(resultpath, 'result.csv')
with open(fname, 'wb') as f:
    writer = csv.writer(f)
    for row in rows:
        writer.writerow(row)
相关问题