여기 예를 들어 내 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
예고편에 ", 3"이 누락되었습니다.
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-를 출력한다 [ '세'] 2,3- [ '세'] 3,4- [ '세'] 제가 new_two 출력되도록 할 때 , new_one, new_three 1,2 2,3 3,4 – user3454635