You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyInstaller打包Py脚本为EXE后遇LookupError: unknown encoding: ascii错误

PyInstaller打包EXE后出现LookupError: unknown encoding: ascii的问题分析与解决

问题场景

在Windows系统使用PyInstaller将Python脚本打包为EXE时遇到编码错误。原脚本用于创建TXT文件,代码如下:

note = ("Hello World! \n\n\n" 
        "This is a testfile!")

with open("hello_world.txt", "w") as f:
    f.write(note)

原脚本运行正常,但打包为EXE执行时抛出错误:

Traceback (most recent call last):
File "create_txt.py", line 7, in
LookupError: unknown encoding: ascii

错误指向with open("hello_world.txt", "w") as f:行。

原因分析

该问题源于PyInstaller打包过程中,未正确包含Python的encodings.ascii模块,导致打包后的EXE运行环境无法识别ascii编码。当open()函数未显式指定编码时,Python会尝试读取系统默认编码,缺失相关编码模块时就会触发此错误。

解决方案

方案1:显式指定文件编码

修改open()函数,明确指定编码格式(如utf-8),避免依赖系统默认编码。修改后的代码:

note = ("Hello World! \n\n\n" 
        "This is a testfile!")

with open("hello_world.txt", "w", encoding="utf-8") as f:
    f.write(note)

方案2:强制PyInstaller包含编码模块

打包时添加--hidden-import参数,强制PyInstaller将encodings.ascii模块纳入打包范围。执行以下打包命令:

pyinstaller --hidden-import encodings.ascii create_txt.py

内容的提问来源于stack exchange,提问作者Nicolaas Peeters

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 01:15:33