PyInstaller打包可执行文件后无法找到Excel文件的问题求助
解决PyInstaller打包后无法访问Stations_list目录下Excel文件的问题
问题根源
PyInstaller打包后,程序运行时会将datas中指定的资源文件解压到系统临时目录(通过sys._MEIPASS访问),而非exe所在目录。你的脚本中通过sys.argv[0]获取的路径是exe的位置,无法定位到解压后的资源文件,导致"File Not Found"错误。
解决方案
1. 修正脚本中的路径获取逻辑
替换脚本中获取基础路径的代码,同时适配开发环境和打包后的运行环境:
import sys import os import pathlib import glob import pandas as pd import tkinter.messagebox as messagebox def get_base_path(): # 判断是否为打包后的可执行文件 if getattr(sys, 'frozen', False): # 打包后,资源文件存放在sys._MEIPASS指向的临时目录 return sys._MEIPASS else: # 开发环境,获取当前脚本所在目录 return os.path.dirname(os.path.abspath(__file__)) def save_data(): dossier_dir = "Dossier" if not os.path.exists(dossier_dir): os.makedirs(dossier_dir) # 获取正确的基础路径 base_path = get_base_path() # 构造Stations_list目录的路径 stations_path = pathlib.Path(base_path) / 'Stations_list' files_to_process = glob.glob(str(stations_path / '*.xlsx')) if len(files_to_process) == 0: messagebox.showerror("File Not Found", "No Excel files found in the 'Stations_list' directory.") return [] result = [] for excel_file in files_to_process: data_frame = pd.read_excel(excel_file) for index, row in data_frame.iterrows(): i = 1 while True: try: if check_ip(row["IP"]): break else: i += 1 if i < 6: result.append([ row["IP"], row["Type de station"], row["Wilaya"], row["Commune"], row["ID"] ]) break except ValueError: print("Error") return result
2. 确认Spec文件的配置正确性
你的spec文件中datas配置逻辑正确,只需确保stations_dir指向真实存在的目录(相对于spec文件的位置):
import sys from pathlib import Path from PyInstaller import __version__ script_path = Path('final_version.py') base_path = script_path.parent stations_dir = base_path / 'Stations_list' a = Analysis( [str(script_path)], pathex=[str(base_path)], binaries=[], # 将Stations_list目录下的所有文件打包到exe内部,运行时解压到同名目录 datas=[(str(stations_dir), 'Stations_list')], hiddenimports=[], hookspath=[], runtime_hooks=None if __version__.startswith('3.6') else [], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, noarchive=False, ) pyz = PYZ(a.pure, a.zipped_data) exe = EXE( pyz, a.scripts, a.binaries, a.zipfiles, a.datas, [], name='script', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, runtime_tmpdir=None, console=True, )
3. 重新打包并测试
执行以下命令重新生成可执行文件:
pyinstaller final_version.spec
运行生成的script.exe,此时程序应该能正确定位到Stations_list目录下的Excel文件。
额外验证步骤
如果仍有问题,可在脚本中添加调试代码打印实际路径:
print(f"Base path: {base_path}") print(f"Stations path: {stations_path}") print(f"Files found: {files_to_process}")
打包后运行exe,查看控制台输出的路径,确认资源文件是否被正确解压到对应位置。
内容的提问来源于stack exchange,提问作者ambitiousfool
相关产品推荐
相关产品推荐

