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'
你的代碼幾乎工作。現在打印出 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