代码之家  ›  专栏  ›  技术社区  ›  user888469

从文本文件打印随机行时出错

  •  2
  • user888469  · 技术社区  · 7 年前

    我的代码是:

    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)
    

    为了避免这个错误,我需要做什么?

    1 回复  |  直到 7 年前
        1
  •  2
  •   cs95 abhishek58g    7 年前

    问题不在于印刷,而在于阅读。您的文件似乎有一些特殊字符。尝试使用其他编码打开文件:

    with open('Long films', encoding='latin-1') as f:
       ...
    

    utf-8 ,因此通常不会出现此错误。