python - UnicodeDecodeError: 'utf-8' codec can't decode byte error when running pyinstaller 但适用于 Pycharm
问题描述
当我使用 Pycharm 运行它时,我有以下 python 代码正在运行:
def get_csv(): # Import data from a csv file
global df
import_file_path = filedialog.askopenfilename(filetypes=[("CSV file", '*.csv')])
if not import_file_path: # If user press cancel select path display error message
tk.messagebox.showwarning(title="Error message", message="CSV file import aborted.")
else:
# print("CSV path :", import_file_path)
with open(import_file_path, "rb") as csv_bin: # automatic CSV encoding detection
result = chardet.detect(csv_bin.read(10000))
encode = result['encoding']
# print("encoding :", encode)
with open(import_file_path) as csv_file:
reader = csv.reader(csv_file, delimiter=';')
first_row = next(reader)
num_cols = len(first_row)
if num_cols > 445:
df = pd.read_csv(import_file_path, sep=';', header=0, na_values=['#NV', ' '], decimal=',', encoding=encode)
tk.messagebox.showinfo(title="Import success", message="CSV file import successful !")
return df
else:
tk.messagebox.showwarning(title="Error message", message="CSV file not compatible")
我已经使用 pyinstaller 来获取与我的 python 代码相对应的 EXE 文件,但我收到了这个错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "tkinter\__init__.py", line 1702, in __call__
File "import_CSV_python.py", line 30, in get_csv
File "c:\users\cyrille\appdata\local\programs\python\python37-32\lib\codecs.py
", line 322, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb0 in position 1759: inval
id start byte
当我使用 Pycharm 运行我的 python 代码时,我没有这个错误。它工作正常。在我的另一台机器上,我使用 pyinstaller 从 python 文件创建工作 EXE 没有任何问题。
我使用此命令调用 pyinstaller 并创建 EXE。
pyinstaller --onefile import_CSV_python.py
我在网上查了一下,发现有些人和我有同样的错误,他们的解决方案是修改 compat.py 文件。这对我来说听起来很复杂,我完全迷路了。我之前一直在努力让一个有点工作的 EXE 显示带有按钮的小窗口来启动我的不同功能。在我的另一台计算机上(我目前在我父母家的另一台机器上工作)运行 pyinstaller 以从 python 文件中获取工作 EXE 根本不是问题,它工作得很好。
编辑:我尝试out = out.decode(encoding)
从 pyinstaller 包中替换 compat.py 文件中的行,out = out.decode(encoding, "replace")
or out = out.decode(encoding, "ingore")
然后保存 compat.py 文件并再次使用 pyinstaller 生成 EXE,但没有结果。我得到了同样的错误:utf8 无法解码
Edit2:感谢 John Szakmeister 我改变了这一行
with open(import_file_path, encoding=encode) as csv_file:
它现在工作正常。
解决方案
推荐阅读
- r - 使用带有 R 中键值的向量替换多列中的值
- smtp - 获取 SMTP 504 .5.7.4“无法识别的身份验证类型”尝试使用 Outlook 365 发送邮件
- json - 如何使用powershell为aws格式化json字符串
- python - kivy ScrollView 不显示来自 Accordion 的列表
- core-data - 带有 FetchedResultsController 的 titleForHeaderInSection 的日期
- python - 我无法在 heroku 上推送我的 python 代码
- html - Webforms 代码背后:在 Aspx 页面 IF 语句中编写 FindControl
- android - 问:/storage/emulated/0/Pictures/document/image:35:打开失败:ENOENT(没有这样的文件或目录)
- autoscaling - 基于 Kubernetes HPA 的 Datadog 指标
- c# - 普通 Html 样式与 asp.net MVC 元素样式