CSV文件的UnicodeDecodeError

时间:2017-01-27 19:46:14

标签: python csv text readfile

当我导入csv文件时,python会抛出以下错误:

  File "/Users/sethkillian/Documents/Python/metar/metar.py", line 31, in get_AirportInfo
    for line in airports:

  File "/Users/sethkillian/anaconda/lib/python3.5/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 358: ordinal not in range(128)

使用Microsoft Excel,我将文件保存为UTF-8 CSV文件。

我也尝试将.decode('UTF-8')放在最后,但它不接受字符串。

这是我的原始代码:

def get_AirportInfo():
    airports = open('airport_codes.csv','r')
    for line in airports:
        print(line.strip().split(','))

有什么想法?我查看了该文件,找不到任何应该绊倒它的特殊字符。

1 个答案:

答案 0 :(得分:0)

在Python3中,class Matrix: def __init__(self, matrix): self.matrix = matrix def transpose(self): new_matrix = [[None] * len(self.matrix[0])] * len(self.matrix) row_num = 0 for row_num in range(len(self.matrix)): for col_num in range(len(self.matrix[0])): print(new_matrix[col_num][row_num]) print(new_matrix) #assignment assigning more than one variable new_matrix[col_num][row_num] = self.matrix[row_num][col_num] print(new_matrix[col_num][row_num]) print(new_matrix) col_num = 0 return new_matrix 没有属性str,但您可以将文件读取为二进制文件,并逐行解码

decode

如果你想使它与Python2兼容,请使用with open('airport_codes.csv', 'rb') as fp: for line in fp: print(line.decode('utf-8').strip().split(',')) 模块,尽管在Python3内置codecs具有open的参数:

encoding

这些解决方案可能会有效,因为如果跟随另一个字节,import codecs with codecs.open('airport_codes.csv', 'r', encoding = 'utf-8'): for line in fp: print(line.strip().split(',')) 可能在0xc3中有效。