Pyinstaller 应用程序正在访问 txt 文件,但不写入它们(在应用程序编译之前工作) [英] Pyinstaller app is accessing txt files, but not writing to them (works before app compilation)

查看:45
本文介绍了Pyinstaller 应用程序正在访问 txt 文件,但不写入它们(在应用程序编译之前工作)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

settings.txt 在编译后的单文件应用程序中存储和访问,但不会被写入.当文件与脚本位于同一目录中时,这会在 Pyinstaller 编译之前起作用.

settings.txt is stored and accessed within the compiled single file app, but it's not being written to. This works prior to Pyinstaller compilation when the file is in the same directory as the script.

应用是从终端编译的:

pyinstaller script.spec script.py --windowed --onefile

a.datas 在规范文件中设置为:

a.datas is set in the spec file as:

a.datas += [('settings.txt','/path/to/settings.txt', "DATA")]

并且文件在应用程序中被正确读取:

and the file is read properly within the app:

with open(resource_path('settings.txt'), 'r') as f2

但是,尝试覆盖文件时文件不会更新:

However, the file isn’t updated when attempting to overwrite the file:

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 个字符长.因此,要测试这是问题所在,请尝试将其设为 one-folder 冻结应用程序,然后将其移动到简单而短的路径中:例如,C:/test.

If you are on Windows, _MEIPASS returns the "short" name for the path in case that any component of it is more than 8 characters long. So, to test that this is the issue, try to make it a one-folder frozen app and then move it in a simple and short path: e.g., C:/test.

如果这是问题所在,您可以使用以下方法检索长路径来解决该问题:

If this is the issue, you can workaround the problem by retrieving the long path using something like:

if hasattr(sys, '_MEIPASS'):
    import win32api
    sys_meipass = win32api.GetLongPathName(sys._MEIPASS)

这篇关于Pyinstaller 应用程序正在访问 txt 文件,但不写入它们(在应用程序编译之前工作)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆