2014-04-04 39 views
1

這裏是我的code.csv怎麼我的代碼「通行證」,如果它不找到CSV蟒蛇一句話

one,two #read the headers from here, and if the code finds headers, 
1,2  #it takes the columns of the old headers, to the new headers in a new order. 
2,3 
3,4 

例如output.csv應該是這樣的:

new_two,new_one,new_three 
2,1 
3,2 
4,3 

通知有兩個後面缺少「,三」。這是我的Python代碼:

import csv 

with open('code.csv', 'rb') as input, open('result.csv', 'wb') as output: 
     reader = csv.DictReader(input) 
     rows = [row for row in reader] 
     writer = csv.writer(output, delimiter = ',') 

     writer.writerow(["new_two", "new_one", "new_three"]) 

     for row in rows: 
       if row['one'] and row['two'] and row['three'] not in row: 
         pass 
       else: 
         writer.writerow([row["one"], row["two"], row["three"]]) 

基本上我想我的代碼總是有這樣的一部分:writer.writerow([row["one"], row["two"], row["three"]]),這需要從輸入文件頭中的列,但如果它沒有找到的頭一個,我想它忘記這一點,並繼續與其餘的列。

它給了我這個錯誤:

Traceback (most recent call last): 
    File "my_code.py", line 11, in <module> 
    if row['one'] and row['two'] and row['three'] not in row: 
KeyError: 'three' 

回答

1

雖然語法上有效,在

row['one'] and row['two'] and row['three'] not in row 

不會做你希望它是什麼。

要檢查row包含鍵'one''two''three',使用

if 'one' in row and 'two' in row and 'three' in row: 
    writer.writerow([row['one'], row['two'], row['three']]) 

如果你想知道你的原代碼,該if被解析爲

if (row['one']) and (row['two']) and (row['three'] not in row): 

在其他單詞,row['one']row['two']被視爲單獨的表達式,它們被「與」在一起。這顯然不是你想要的。此外,你有你的AND和OR混合(我的版本使用AND,因爲我已經扭轉了支票,將writerow()放在if而不是else)。

+0

你的代碼幾乎工作。現在打印出 new_two,new_one,new_three 1,2,[ '3'] 2,3,[ '3'] 3,4,[ '3'] 而我想輸出是 new_two ,new_one,new_three 1,2 2,3 3,4 – user3454635