2016-03-17 86 views
0

好日子,連接兩個列在Python

我想從一個CSV文件連接兩個列,並把這個字符串轉換成另一種csv文件,但成一列。我試過

代碼:

import csv 

file1=open('Source.csv','r') 
readfile=csv.reader(file1,delimiter=';') 
file2=open('Output.csv','w',newline='') 
result=() 
for row in readfile: 
    if (row[2]>condition1 and 'string' in row[6]):   
     result=str(row[2])+'- '+str(row[6]) 
     print(result)#line just to see to info from the output file 
     writefile=csv.writer(file2,delimiter=';') 
     writefile.writerow(result) 

file1.close() 
file2.close() 

我的問題是,result不是在單個列到輸出文件中寫道,但每個角色在單獨的專欄中寫道。

請注意,print()似乎是我想要放在輸出文件中。

有這樣的幫助嗎? 提前謝謝!

回答

0

試試這個:

import csv 

file1=open('Source.csv','r') 
readfile=csv.reader(file1,delimiter=';') 
file2=open('Output.csv','w',newline='') 
writefile=csv.writer(file2,delimiter=';') 
result=() 
for row in readfile: 
    if (row[2]>condition1 and 'string' in row[6]):   
    result=[str(row[2])+'- '+str(row[6])] 
    print(result)#line just to see to info from the output file 
    writefile.writerow(result) 

file1.close() 
file2.close() 
+0

現在工作...謝謝拉胡爾 –

+0

尼斯。如果它適合你,請接受答案。 – Rahul

1

只是對拉胡爾的回答擴大,我強烈建議使用ContextManager(with)的。它確保即使在處理它們時發生異常,您的文件也會被關閉。

像這樣:

import csv 

with open('Source.csv') as file1: 
    readfile = csv.reader(file1,delimiter=';') 
    with open('Output.csv','w',newline='') as file2: 
     writefile = csv.writer(file2,delimiter=';') 
     for row in readfile: 
       if row[2] > condition1 and 'string' in row[6]:   
        result = [str(row[2]) + '- ' + str(row[6])] 
        print(result)#line just to see to info from the output file 
        writefile.writerow(result)