使用PyInstaller打包exe后Windows端无法读取文本文件的问题
问题:PyInstaller打包Minecraft Python程序后Windows无法读取文本文件
问题背景
我用PyInstaller将Minecraft相关Python代码打包为.exe文件,程序在macOS上运行正常,但Windows端无法打开并读取文本文件,问题集中在make_house函数部分。
问题代码
def make_house(): try: server_Adress = entry_server.get() pythonpPort = int(entry_port.get()) playerName = entry_player.get() mc = Minecraft.create(server_Adress, pythonpPort, playerName) xp,yp,zp=mc.player.getPos() print("yes") # file_name = os.getcwd() + '/house.txt' print("yes") my_file = open("/Users/me/Desktop/Python/python-projects/house.txt","r") print("yes") print(my_file) for line in my_file: nums = line.strip().split(" ") x = int(nums[0]) + xp y = int(nums[1]) + yp z = int(nums[2]) + zp b = int(nums[3]) mc.setBlock(x, y, z, b) print("done") except: showerror( "error", "please check your server address , port and player name")
使用的打包命令
pyinstaller filename.py --add-data 'pyramid.txt:.' --add-data 'house.txt:.' --windowed --onefile -i logo.ico
解决方案
核心问题
代码写死了macOS专属的绝对路径/Users/me/Desktop/Python/python-projects/house.txt,Windows系统不存在该路径;同时PyInstaller单文件打包后,资源会被解压到临时目录,不能直接用固定路径或当前工作目录读取。
修复步骤
添加资源路径适配函数
用于获取打包后程序的正确资源路径:import os import sys def get_resource_path(relative_path): # 适配PyInstaller单文件打包的临时目录 if hasattr(sys, '_MEIPASS'): return os.path.join(sys._MEIPASS, relative_path) # 未打包时使用当前目录 return os.path.join(os.path.abspath("."), relative_path)修改文件读取代码
将固定路径替换为适配函数返回的路径:my_file = open(get_resource_path("house.txt"), "r")优化异常捕获
替换宽泛的异常捕获,精准定位问题:except Exception as e: showerror("error", f"错误信息: {str(e)}\n请检查服务器信息或文件配置")调整Windows打包命令
Windows CMD下需将单引号改为双引号:pyinstaller filename.py --add-data "pyramid.txt:." --add-data "house.txt:." --windowed --onefile -i logo.ico
额外注意事项
- 用
os.path.join拼接路径,避免手动写/或\,同时适配Windows和macOS的路径分隔符 - 单文件打包时,所有资源文件必须通过
sys._MEIPASS访问,否则会找不到文件
内容的提问来源于stack exchange,提问作者programmer9674
相关产品推荐
相关产品推荐

