2012-04-23 152 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)