【问题标题】:I am getting error while I opening a file打开文件时出现错误
【发布时间】:2021-08-17 07:19:14
【问题描述】:
import os
import sys
file = os.path.expanduser('~/Desktop/python_programing/python_projects/12dicts-6.0.2/agid.txt')
try:
    with open(file) as in_file:
        loaded_txt = in_file.read()
        loaded_txt = [x.lower() for x in loaded_txt]
        print (loaded_txt)
except IOError as e:
    print("{}\nError opening {}. Terminating program." .format(e, file), file=sys.stderr)
    sys,exit(1)


file_to_open = os.path.expanduser('~/Desktop/movie_quotes.txt')

运行上述代码时出现以下错误

Traceback (most recent call last):
  File "/Users/pavandadi/Desktop/python_programing/python_projects/exception.py", line 6, in <module>
    loaded_txt = in_file.read()
  File "/Users/pavandadi/opt/anaconda3/lib/python3.8/codecs.py", line 322, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 2921: invalid continuation byte

怎么办?

【问题讨论】:

  • 您的文本文件是否正确编码为 UTF-8?它是否可能以不同的方式编码?也许您需要为open 命令指定不同的encoding 值(和模式标志),或者将decode("whatever-encoding") 附加到read() 调用?

标签: python list file


【解决方案1】:

我认为您需要在阅读后对其进行解码

with open(file) as in_file:
        loaded_txt = in_file.read()
        loaded_txt = [x.lower() for x in loaded_txt]
        print (loaded_txt.decode('UTF-8')) #or any encoding type you want

【讨论】:

  • I usewith open(file,'rb') as in_file: loaded_txt = in_file.read() loaded_txt = [x.lower() for x in loaded_txt] print (loaded_txt)
猜你喜欢
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 2019-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-10
  • 1970-01-01
相关资源
最近更新 更多