在编译成单个python可执行文件后,如何访问文件



我有一个python脚本,它读取本地文件(我们称之为file.foo(。当我编译脚本时,我需要可执行文件中的本地文件,所以我使用pyinstaller,如下所示:

> pyinstaller --onefile --add-data "file.foo"  "script.py"

问题是,当我运行可执行文件时,我的脚本找不到嵌入其中的file.foo

有没有办法读取可执行文件中编译的文件?

PS:我更喜欢使用--onefile来保持它的闭源

pyinstaller将在运行时将您的文件解压缩到操作系统TEMP文件夹内的一个临时文件夹中,因此为了在使用此答案中的代码解压缩后获得文件的路径

def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)

然后要获得数据的路径,只需使用

data_path = resource_path("file.foo")
with open(data_path,'r') as f:
pass # read it as you normally would

请注意,--onefile可能会导致某些库无法工作,因此请确保先测试依赖关系。

最新更新