(對不起,我不能添加評論,但。)
[後來編輯,下面的語句是錯誤的!]「的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