python - Pyinstaller 应用程序正在访问 txt 文件,但不写入它们(在应用程序编译之前工作)

标签 python pyinstaller

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/

相关文章:

java - Python3 Opencv3 Ubuntu 15 - 出现错误

python - 递归算法中Python列表的可变性

python - 使用 scikit learn 进行时间序列预测

python - Pyinstaller exe 转换失败 - 使用 lightgbm 和 sklearn

python - 如何使用 Pyinstaller 打包的 Kivy Python 应用程序在 OSX 菜单栏中创建菜单项?

Python Pandas 比较两个数据框然后编辑

python - 如何从 .yuv 视频文件中提取某些帧并使用 FFmpeg、OpenCV 和 python 创建新视频?

python - __main__.pyinstallerimporterror 无法加载 dynlib/dll "shcore"

python - 在我使用 PyInstaller 将 PY 转换为 EXE 后,它抛出错误

python - 如何从编译的 .exe 文件将帮助打印到终端窗口?