2012-04-23 155 views
0

我有125个数据文件,其中包含两列和21行数据,我想将它们导入到一个.csv文件(如125对列,只有21列行)。 这就是我的数据文件看起来像:Python-将多个文件导入到一个.csv文件

enter image description here

我是相当新的蟒蛇,但我想出了下面的代码:

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行的两列中。

任何帮助非常感谢!

+2

这完全是针对'paste'工作。 – 2012-04-23 01:08:34

+1

在Python中是否有粘贴命令? – Esan 2012-04-23 01:24:32

+0

有一个Python粘贴,但这不是我说的。 – 2012-04-23 01:25:13

回答

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

+0

对不起,忘记在连接线之间加入逗号。应该有希望现在好起来 – SudoNhim 2012-04-23 01:35:44

+0

谢谢你的代码,但格式有一个小问题,因为只有125列(即在Excel中打开时,一对列连接在一起) – Esan 2012-04-23 11:35:39

+0

对不起,我修复了大约1的错误分钟后我发布。尝试重新粘贴它,如果你还没有修复它:) – SudoNhim 2012-04-24 12:34:23

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) 
+0

谢谢你这。请看看我现在包括在问题中的图片。 – Esan 2012-04-23 11:38:13

1

(对不起,我不能添加评论,但。)

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

我的+1使用标准的csv模块。但是文件应该始终关闭 - 尤其是当你打开它们时。此外,还有一个错误。通过 - 从文件读取的行 - 即使你只在这里写结果。该解决方案实际上缺失。基本上,从文件中读取的行应附加到与行号相关的子列表。行号应该通过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)