我需要从文件“Long films”中随机打印一行。
我的代码是:
import random
with open('Long films') as f:
lines = f.readlines()
print(random.choice(lines))
但是它打印出这个错误:
Traceback (most recent call last):
line 3, in <module>
lines = f.readlines()
line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 36: ordinal not in range(128)
我需要做什么才能避免这个错误?
请您参考如下方法:
问题不在于打印,而在于阅读。您的文件似乎有一些特殊字符。尝试使用不同的编码打开您的文件:
with open('Long films', encoding='latin-1') as f:
...
此外,您是否对您的语言环境进行了任何设置?您是否在文件顶部设置了任何编码方案?通常,python3 会“帮助”将您的文本解码为 utf-8,因此您通常不应收到此错误。
