如何解决cx_Freeze打包的可执行文件无法写入文本文件的问题
cx_Freeze打包Windows应用写入文件报PermissionError: [Errno 13]问题说明
问题现象
使用cx_Freeze打包Python应用后,已将所有依赖文件夹放入build目录,运行exe时只有执行open(SaveFile, "w")写入操作会抛出PermissionError: [Errno 13] Permission denied错误,读取文件操作完全正常。
关联配置
使用的setup.py配置如下:
import sys from cx_Freeze import setup, Executable # Dependencies are automatically detected, but it might need fine tuning. # "packages": ["os"] is used as example only build_exe_options = dict(include_files = ["IMG/", "Saves/"]) # base="Win32GUI" should be used only for Windows GUI app base = None if sys.platform == "win32": base = "Win32GUI" setup( name = "PPD Mover", description = "An app to help move files for using PPD", options = {"build_exe": build_exe_options}, executables = [Executable("File.py", base=base)] )
根因说明
通过include_files打入build目录的文件夹,默认归属程序安装目录,Windows系统对Program Files这类系统级目录有写入权限限制,普通权限运行的程序仅能读取目录内文件,无法执行写入操作,所以会出现读写权限表现不一致的问题。
解决方案
- 推荐方案:将需要写入的用户数据存储到当前用户的无权限限制目录,无需额外申请管理员权限:
import os # 拼接当前用户AppData目录下的应用专属存储路径 save_dir = os.path.join(os.getenv('APPDATA'), 'PPD Mover', 'Saves') # 目录不存在时自动创建 os.makedirs(save_dir, exist_ok=True) # 拼接完整保存文件路径 save_file = os.path.join(save_dir, '目标保存文件名') # 执行写入操作 with open(save_file, 'w', encoding='utf-8') as f: f.write('要保存的内容')
- 备选方案:如果必须写入程序安装目录,右键点击exe选择「以管理员身份运行」即可正常写入,也可以在打包阶段给exe嵌入管理员权限manifest配置,免除每次手动选权限的操作。
内容的提问来源于stack exchange,提问作者UCSA
相关产品推荐
相关产品推荐

