2014-04-04 2 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 

예고편에 ", 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' 

답변

1

동안 구문 적으로 유효한의

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

은 당신이 기대하는 것을하지 않습니다.

if 다른에서

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

로 구문 분석, 당신은 당신의 원본 코드에 대해 궁금해하는 경우

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

를 사용 row는 키 'one', 'two''three' 포함되어 있는지 확인하려면 단어, row['one']row['two']은 함께 AND 연산 된 별도의 표현식으로 처리됩니다. 이것은 분명히 당신이 원하는 것이 아닙니다. 게다가, AND와 OR이 섞여 있습니다. (내 버전은 AND를 사용했기 때문에, 반대로 else이 아닌 ifwriterow()을 넣었습니다.)

+0

코드가 거의 작동했습니다. 이제 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