2012-08-10 6 views
4

방금 ​​PC를 직장에두고 (파이썬 2.7 사용) 방금 끝내고 있던 스크립트를 사용했습니다. 아래에서 재현). 그것은 직장에서 잘 달렸고, 나는 하나 또는 두 가지를 추가하고 싶었습니다. 하지만 집에 와서 파이썬의 내 맥 버전 (3.2.2)를 사용하고 나는 다음과 같은 오류가 발생합니다 :UnicodeDecodeError : 'ascii'코덱은 304 위치의 0xc3에서 바이트를 디코딩 할 수 없습니다. 서수가 범위 내에 있지 않습니다. (128)

Traceback (most recent call last): 
    File "/Users/Downloads/sda/alias.py", line 25, in <module> 
    for row_2 in in_csv: 
    File "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/encodings/ascii.py", line 26, in decode 
    return codecs.ascii_decode(input, self.errors)[0] 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 304: ordinal not in range(128) 

내 코드는 여기에 있습니다 : 그것은 Fund_Aliases.csv처럼 보이는

import csv 
inname = "Fund_Aliases.csv" 
outname = "output.csv" 

def first_word(value): 
    return value.split(" ", 1)[0] 

with open(inname, "r") as infile: 
    with open(outname, "w") as out file: 
     in_csv = csv.reader(infile) 
     out_csv = csv.writer(outfile) 

    column_names = next(in_csv) 
    out_csv.writerow(column_names) 

     id_index = column_names.index("id") 
     name_index = column_names.index("name") 

     try: 
      row_1 = next(in_csv) 
      written_row = False 

      for row_2 in in_csv: 
      if first_word(row_1[name_index]) == first_word(row_2[name_index]) and row_1[id_index] != row_2[id_index]: 
       if not written_row: 
        out_csv.writerow(row_1) 

       out_csv.writerow(row_2) 
       written_row = True 
      else: 
       written_row = False 

      row_1 = row_2 
     except StopIteration: 
     # No data rows! 
     pass 

답변

5

는 아니다 아스키 파일. Python3 docs에 따르면

:

Since open() is used to open a CSV file for reading, the file will by default be decoded into unicode using the system default encoding (see locale.getpreferredencoding()). To decode a file using a different encoding, use the encoding argument of open:

with open('some.csv', newline='', encoding='utf-8') as f: 
    reader = csv.reader(f) 

그래서 encoding 매개 변수를 지정하십시오.

+0

감사합니다. 그 트릭을, 난 그냥 다음 두 줄을 적절하게 업데이트했다 : open (inname, "r", encoding = "utf-8") infile : open (outname, "w", encoding = "utf -8 ") outfile : – user1590499

+0

명확히하기 위해 PC에있는 CSV 파일은 이메일로 보내고 Mac에 다운로드 한 CSV 파일과 동일한 ASCI 형식이 아닙니다. 이것은 근본적으로 Apple 운영 체제에서 1-2 줄의 코드가이 파일을 Windows 운영 체제의 것과 다르게한다는 것을 의미합니까? – user1590499

+0

물론 1-2 줄의 코드에 따라 큰 차이를 만들 수 있습니다. 그러나 일반적으로 차이가있는 경우 일반적으로 EOL 문자의 차이 (유닉스의 경우 '\ n', Windows의 경우 '\ r \ n')와 인코딩의 차이점으로 제한됩니다. 인코딩에 대해 명시 적으로 지정하면이 문제를 피할 수 있습니다. – unutbu

관련 문제