UnicodeDecodeError:'ascii'编解码器无法解码位置304中0xc3中的字节:序数不在范围内(128) [英] UnicodeDecodeError: 'ascii' codec can't decode byte in 0xc3 in position 304: ordinal not in range(128)

查看:124
本文介绍了UnicodeDecodeError:'ascii'编解码器无法解码位置304中0xc3中的字节:序数不在范围内(128)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚让PC处于工作状态(使用Python 2.7),并且有一个我刚刚完成的脚本(如下所示).工作正常,我只想添加一两个内容.但是我回到家,使用的是Mac版本的Python(3.2.2),出现以下错误:

I just left the PC at work (using Python 2.7) and had a script that I was just finishing up (reproduced below). It ran fine at work, I just wanted to add one or two things. But I came home and am using my Mac's version of Python (3.2.2) and I get the following error:

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

推荐答案

看来Fund_Aliases.csv不是ascii文件.

It looks like Fund_Aliases.csv is not an ascii file.

根据 Python3文档:

由于使用open()打开CSV文件进行读取,因此该文件将通过 使用系统默认编码将default解码为unicode(请参见 locale.getpreferredencoding()).使用其他解码文件 编码,请使用open:的编码参数:

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参数.

So try specifying the encoding parameter.

这篇关于UnicodeDecodeError:'ascii'编解码器无法解码位置304中0xc3中的字节:序数不在范围内(128)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆