2012-08-10 91 views
4

我刚离开电脑工作(使用Python 2.7),并有一个脚本,我刚刚完成转载如下)。它在工作中运行良好,我只想添加一两件事情。但是,我回到家,我用我的Mac的Python版本(3.2.2),我收到以下错误:UnicodeDecodeError:'ascii'编解码器无法解码0xc3中位置304中的字节:序号不在范围内(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) 

我的代码是在这里:

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

看起来Fund_Aliases.csv不是ascii文件。

按照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

谢谢!这样做的伎俩,我只需要相应地更新以下两行:打开(名称,“r”,编码=“utf-8”)作为infile: 与开放(outname,“w”,encoding =“utf -8“)作为outfile: – user1590499 2012-08-10 22:39:27

+0

只是为了说明,PC上的CSV文件与通过电子邮件发送并下载到Mac上的CSV文件不同。这是否意味着Apple操作系统中的1-2行代码使该文件与Windows操作系统的文件不同? – user1590499 2012-08-10 22:41:34

+0

这当然可以根据这些1-2行代码中的内容做出很大的区别。但总的来说,如果存在差异,它通常仅限于EOL字符的差异(对于unix,''\ n''对比Windows的''\ r \ n'')或编码的差异。明确编码应该有助于避免这个问题。 – unutbu 2012-08-11 00:49:53

相关问题