(对不起,我不能添加评论,但。)
[后来编辑,下面的语句是错误的!]“的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)
这完全是针对'paste'工作。 – 2012-04-23 01:08:34
在Python中是否有粘贴命令? – Esan 2012-04-23 01:24:32
有一个Python粘贴,但这不是我说的。 – 2012-04-23 01:25:13