微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PyInstaller 不识别相对路径

如何解决PyInstaller 不识别相对路径

我正在尝试为我的 python 应用程序生成一个 .exe。在代码中,我导入了一些嵌入文件,如下所示:

f = open('source/store/data_dictionary.json')

尝试从生成的 .exe 运行应用程序,我收到如下错误

FileNotFoundError: [Errno 2] No such file or directory: 'source/store/data_dictionary.json'

full output error from the console

生成 .exe,我运行了:

pyinstaller --onefile app.py

我不知道是否有更好的方法在 python 脚本中导入文件生成可执行文件,或者我是否必须编写一些设置。

你可以在这里查看我的源代码https://github.com/GraphFilter/GraphFilter

解决方法

查看源代码后,我注意到路径是相对于文件 app.py 的位置的。因此,只要创建可执行文件后该相对路径是相同的。 IE。如果你把它做成一个包,其中 exe 与 app.py 位于同一个位置。那么无论捆绑包在哪里

为此,您可以使用以下代码在运行时获取 exe 文件的目录,并使用它来获取您的相关文件

import os

cur_dir = os.path.dirname(__file__) # print this to see what it looks like
             # something like: 'c:/path/to/file'

# then using an f-string to get the absolute path of the required files
f = open(f'{cur_dir}/source/store/data_dictionary.json') # essentially 'c:/path/to/file/source/store....'

编辑:(未测试,但您也可以更改工作目录并使用与以前相同的代码)

import os

cur_dir = os.path.dirname(__file__)
os.chdir(cur_dir) # change working directory

# print os.cwd() to see the current working directory,it should be the path to the file

#then proceed as before
f = open('source/store/data_dictionary.json')
.
.
.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。