尝试打开文件时出错

时间:2015-04-11 09:32:13

标签: python-3.x text-files

我已经通过Microsoft Word创建了一个txt文件,并将其保存为texta.txt文件夹untitled。我还将texti.py中的python文件保存在同一文件夹untitled中。

当回到Wing IDE时,我输入了以下内容:

infile = open('texta.txt')
lines = infile.readlines()

然后又回来了:

    Traceback (most recent call last):
  File "/Applications/Wing101.app/Contents/MacOS/src/debug/tserver/_sandbox.py", line 2, in <module>
    if __name__ == '__main__':
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]
builtins.UnicodeDecodeError: 'ascii' codec can't decode byte 0xd5 in position 192: ordinal not in range(128)

我想打开文件(文本),然后将其打印到python shell中。

1 个答案:

答案 0 :(得分:0)

将文件另存为.txt时,应指定编码而不是让编辑为您选择,而不是告诉您。 LibreOffice有两个文本SaveAs选项:'Text(.txt)'和'Text - choose encoding(.txt)'。 MS Word还应该有一个选项来选择编码。如果没有,请找一个编辑器。除非您有理由选择其他方式,否则请选择UTF8。

特定的错误消息告诉我您的文本文件不是utf8。可能的替代方案是'latin1'。如果是,b'\xd5'.decode('latin1') == 'Õ'。如果'Õ'是您文件中的第195个字符,请使用encoding=latin1。如果没有,你可以猜到其他的东西。或者在同一台计算机上重新打开MS Word并使用已知编码保存。