马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
各位大佬们,练习easygui代码是,第二题是 提供一个文件夹浏览框,让用户选择需要打开的文本文件,打开并显示文件内容。
我是这样写的:
import easygui as g
import os
import pickle
string = ''
local = g.fileopenbox('请选择一个文件夹', '浏览文件夹', 'E:\\测试\\*.txt')
try:
with open(local, encoding = 'utf-8') as f:
for i in f:
string += i
content = f.read()
g.textbox('文件【%s】的内容如下:' % os.path.basename(local), title = '显示文件内容', text = content)
except UnicodeDecodeError:
with open(local, 'rb') as f:
my_list = pickle.load(f)
g.textbox('文件【%s】的内容如下:' % os.path.basename(local), title = '显示文件内容', text = my_list)
因为有的文件时二进制方式保存的所以我让报编码的时候,用二进制,泡菜那张的方式读,二进制是没有问题的
但是打开正常文本文件,有的可以打开,有的会报这个错误:
Traceback (most recent call last):
File "D:\local\FileStorage\python\easygui_打开文件(可以修改).py", line 9, in <module>
for i in f:
File "D:\download\software\student\Python\install\lib\codecs.py", line 322, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc4 in position 0: invalid continuation byte
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:\local\FileStorage\python\easygui_打开文件(可以修改).py", line 15, in <module>
my_list = pickle.load(f)
_pickle.UnpicklingError: invalid load key, '\xc4'.
有的可以正常打开,正常输出
----------------------------------------------------------------------------------------------------------
然后我把encoding = 'utf-8'删除了,改成了:
这种形式,这个时候原来出错的文件可以正常读取了,但是本来正常的文件报错:
Traceback (most recent call last):
File "D:\local\FileStorage\python\easygui_打开文件(可以修改).py", line 9, in <module>
for i in f:
UnicodeDecodeError: 'gbk' codec can't decode byte 0xa5 in position 7: illegal multibyte sequence
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:\local\FileStorage\python\easygui_打开文件(可以修改).py", line 15, in <module>
my_list = pickle.load(f)
_pickle.UnpicklingError: could not find MARK
又说gbk不行了,要用utf-8,总之是一言难尽啊,还有二进制编码的从来没出过问题
|