settings.txt 在已编译的单文件应用程序中存储和访问,但不会被写入。当文件与脚本位于同一目录中时,这会在 Pyinstaller 编译之前起作用。
应用程序是从终端编译的:
pyinstaller script.spec script.py --windowed --onefile
a.datas
在规范文件中设置为:
a.datas += [('settings.txt','/path/to/settings.txt', "DATA")]
并且文件在应用程序中被正确读取:
with open(resource_path('settings.txt'), 'r') as f2
但是,当尝试覆盖文件时,文件不会更新:
def OnExit(self, event):
with open(resource_path('settings.txt'), 'w') as f2:
f2.write('update')
self.Destroy()
resource_path
定义为:
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.environ.get("_MEIPASS2", os.path.abspath("."))
return os.path.join(base_path, relative_path)
最佳答案
如果您使用的是 Windows,_MEIPASS
返回路径的“短”名称,以防路径的任何部分长度超过 8 个字符。因此,要测试这是否是问题所在,请尝试将其设为单文件夹
卡住应用程序,然后将其移动到简单而短的路径中:例如C:/test
。
如果这是问题所在,您可以通过使用以下方法检索长路径来解决该问题:
if hasattr(sys, '_MEIPASS'):
import win32api
sys_meipass = win32api.GetLongPathName(sys._MEIPASS)
关于python - Pyinstaller 应用程序正在访问 txt 文件,但不写入它们(在应用程序编译之前工作),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41073132/