我已经开始使用 Geany(在 Linux 上工作)编写代码。它在 Geany 上运行良好,当我尝试在 pythontutor.org 上模拟它时,一切似乎都是正确的,但 IDLE(在 Macbook 上)不会执行它。 这是我的代码:
import random
f = open('mots.txt')
word_list = f.readlines()
line = random.randint(0,len(word_list))
word = word_list[line]
print(word)
它应该打开文件,列出其中包含的单词(我每行一个单词),选择一个对应于一行的数字,然后给我它随机选择的单词。
这是我从 IDLE 中得到的:
Traceback (most recent call last):
File "/Users/luvi/Desktop/maths/INFO-F-101/Projets/projet2_test.py", line 3, in <module>
word_list = f.readlines()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 305: ordinal not in range(128)
谢谢!!
最佳答案
你没有具体问一个问题,但我想你想知道为什么,以及该怎么做。 doc for open说“默认编码取决于平台(无论 locale.getpreferredencoding() 返回什么)。”如果您有一个已知非 ASCII 编码的文件,安全的跨平台做法是在打开调用中提供显式编码参数。
由于 Python 而不是 IDLE 执行 open
,我怀疑您应该将标题更改为“Python 代码在 Linux 而不是 OSX 上运行”。要进行测试,请直接使用 Python 从命令行运行它,而不是从 IDLE 或 Geany。
关于在 Geany 中工作的 Python 代码不在 IDLE 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46875981/