python
import easygui as gimport os
file_path = g.fileopenbox(default ="*.txt")
with open(file_path) as f:
title = os.path.basename(file_path)
msg = f"文件【{title}】的内容如下:"
text = f.read()
g.textbox(msg,title,text)
为什么运行结果报错?
Traceback (most recent call last):
File "C:/Users/Administrator/AppData/Local/Programs/Python/Python37/GUI作业2.py", line 9, in <module>
text = f.read()
UnicodeDecodeError: 'gbk' codec can't decode byte 0x99 in position 441547: illegal multibyte sequence
文件编码错误,写入与读取编码不一致导致解码字符时字节长度不同导致报错
open 函数内加上 encoding='utf-8' 参数即可
或者将 txt 另存为时设置保存编码为 ANSI 一般可以不用加 encoding 参数
Twilight6 发表于 2021-6-10 17:47
文件编码错误,写入与读取编码不一致导致解码字符时字节长度不同导致报错
open 函数内加上 encoding=' ...
可以改写帮忙改写哈吗 快乐开心 发表于 2021-6-11 09:51
可以改写帮忙改写哈吗
import easygui as g
import os
file_path = g.fileopenbox(default ="*.txt")
with open(file_path, encoding='utf-8') as f:
title = os.path.basename(file_path)
msg = f"文件【{title}】的内容如下:"
text = f.read()
g.textbox(msg,title,text) Twilight6 发表于 2021-6-11 10:00
还是会报错!
Traceback (most recent call last):
File "C:/Users/Administrator/AppData/Local/Programs/Python/Python37/GUI作业2.py", line 9, in <module>
text = f.read()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\codecs.py", line 322, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte
快乐开心 发表于 2021-6-11 15:31
还是会报错!
Traceback (most recent call last):
那就把你准备打开的txt 文件重新保存
在另存为的窗口右下角有编码设置,选择 utf-8 或 ANSI
若选 ANSI 那么就不用加 encoding 参数,选 UTF-8 需要 Twilight6 发表于 2021-6-11 10:00
ok 了 是打开文件的问题
页:
[1]