2012-12-05 54 views
0

我有了這樣的數據的.csv:如何創建新的連接列?

30,972.74176,0.446378,1.825426,cl+l 
31,1015.075579,0.279686,2.950118,l 
32,1072.59334,0.273239,4.408458,cl+l 
33,1139.55317,-1.616904,4.756378,l 
34,1279.86304,50.335186,3.877577,r 
35,1181.541419,61.399389,5.155133,r 
36,1097.421199,63.809733,5.37508,r 
37,1018.555678,64.034432,2.59232,r 

我寫了一個程序,它在哪裏的最後一列(E,因爲我在我的程序調用它)或者是行的「 l「或」cl + l「並將其複製到另一個名爲」left.csv「的文件中。我想要做的就是添加另一列left.csv這需要從第二列(B)的數據,擺在它們之間的逗號,然後從列D.

所以,left.csv右數據現在看起來像:

30,972.74176,0.446378,1.825426,cl+l 
31,1015.075579,0.279686,2.950118,l 
32,1072.59334,0.273239,4.408458,cl+l 
33,1139.55317,-1.616904,4.756378,l 

我要的是:

30,972.74176,0.446378,1.825426,cl+l,"972.74176,1.825426" 
31,1015.075579,0.279686,2.950118,l,"1015.075579,2.950118"  
32,1072.59334,0.273239,4.408458,cl+l,"1072.59334,4.408458" 
33,1139.55317,-1.616904,4.756378,l,"1139.55317,4.756378" 

我應該如何去實現這一點,我怎麼能告訴了逗號不能啓動,即使它的下一個條目的程序CSV?這是可能的,我將不得不有括號或不同的分隔符?我現在所擁有的代碼是:

import csv 
import sys 
import operator 

fieldnames = ["A","B","C","D","E"] 
surveyfile = open("source.csv", "r") 
left_file = open("left.csv",'wb') 
right_file = open("right.csv",'wb') 
coil_file = open("coil1.csv","wb") 


reader = csv.DictReader(surveyfile, fieldnames=fieldnames, delimiter=",") 
left_writer = csv.DictWriter(left_file, fieldnames, delimiter=",") 
sortedlefts = sorted(reader,key=lambda x:float(x["B"])) 

surveyfile.seek(0,0) 

right_writer = csv.DictWriter(right_file, fieldnames, delimiter=",") 
sortedrights = sorted(reader,key=lambda x:float(x["B"]), reverse=True) 

coil_writer = csv.DictWriter(coil_file, fieldnames, delimiter=",") 

for row in sortedlefts: 
    if row["E"] == "l" or row["E"] == "cl+l": 
     left_writer.writerow(row) 
     coil_writer.writerow(row) 


for row in sortedrights: 
    if row["E"] == "r": 
     right_writer.writerow(row) 
     coil_writer.writerow(row) 

回答

3

只需添加一個額外的價值row,格式包括逗號:

row['F'] = '%s,%s' % (row['E'], row['B']) 

或使用','.join()

row['F'] = ','.join([row['E'], row['B']]) 

但包括'F'在您的地區爲left_writer

left_writer = csv.DictWriter(left_file, fieldnames + ['F'], delimiter=",") 

如果您配置coil_writer實例忽略額外的列,你並不需要創建一個單獨的迴路,或在現有的循環建立的row副本:

coil_writer = csv.DictWriter(coil_file, fieldnames, delimiter=",", extrasaction='ignore') 

的CSV作家會照顧你的報價。

+0

當我在for循環中添加該內容時,我總是得到:AttributeError:'dict'對象沒有屬性'append'。另外,我只想追加left.csv,而不是兩個。我需要爲coil_writer做一個單獨的循環嗎? – user1879422

+1

@ user1879422:更新(最初沒有意識到它是一個dictwriter)。 –

+0

你先生,是個天才。謝謝。 – user1879422