jaywolf 2017-11-11 07:55 采纳率: 0%
浏览 11190

UnicodeDecodeError: 'gbk' codec can't decode byte

运行 "Learn Python the Hard Way" 里的代码时出现的报错。代码:

1.  from sys import argv
2.  from os.path import exists                              
3.  
4.  script, from_file, to_file = argv
5.  
6.  print(f"Copying from {from_file} to {to_file}")
7.  
8.  # we could do these two on one line, how?
9.  in_file = open(from_file)
10. indata = in_file.read()
11.
12. print(f"The input file is {len(indata)} bytes long")
13.
14. print(f"Does the output file exsit? {exists(to_file)}")
15. print("Ready, hit RETURN to continue, CTRL-C to abort.")
16. input()
17. 
18. out_file = open(to_file, 'w')
19. out_file.write(indata)
20. 
21. print("Alright, all done.")
22. 
23. out_file.close()
24. in_file.close() 

照抄书本在 Terminal 上输入的命令:
$ echo "This is a test file." > test.txt
$ cat test.txt
This is a test file.
$ python ex17.py test.txt new_file.txt

下面是 Terminal 给的提示:
Copying from test.txt to new_file.txt
Traback ( most recent call last):
File "ex17.py", line 10, in
indata = in_file.read()
UnicodeDecodeError: 'gbk' codec can't decode byte 0xff in position 0: illegal multibyte sequence

尝试把 'gbk' 编码改为 'UTF-8':
9. in_file = open(from_file, 'r', encoding = 'UTF-8')

Terminal 给出的提示

Copying from test.txt to new_file.txt
Traceback (most recent call last):
File "ex17.py", line 10, in
indata = in_file.read()
File "C:\Python36\lib\codecs.py", line 321, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

求解:是什么导致这个 Error ?以及如何解决?

  • 写回答

3条回答 默认 最新

  • CaiNiaoWuZui 2017-11-11 16:01
    关注

    UnicodeDecodeError 解码错误,请先确认源文件的编码是什么,然后用对应的编码解码。如果是gb2312,encoding='gb18030'试试,
    如果编码确认无误,还出现解码错误,那么一定是文件出现无法解码的乱码。此时1:去除文件中的乱码 ; 2:以字节方式读入,然后decode时
    传入errors='ignore'忽略解码错误即可。强调一下,一定要先确认编码无误。

    评论

报告相同问题?

悬赏问题

  • ¥15 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!