You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyInstaller单文件程序无法在运行目录创建文件的问题及解决

PyInstaller单文件打包后目标文件未生成的问题解决

问题场景

我尝试使用PyInstaller将名为test.py的Python脚本打包为单文件可执行程序,脚本功能是创建文本文件并写入0到100的数字,代码如下:

from os.path import dirname, abspath

def main():
    txtfile = dirname(abspath(__file__)) + '/text.txt'
    with open(txtfile, 'w') as f:
        for num in range(101):
            f.write(str(num) + '\n')

if __name__ == '__main__':
    main()
    print('script executed')

在脚本所在目录执行命令:

pyinstaller test.py --onefile

成功生成包含test可执行文件的dist目录。进入dist目录执行./test,程序正常输出“script executed”且退出码为0,但预期的text.txt文件并未在当前目录创建。

问题原因

PyInstaller的单文件模式下,程序运行时会先将自身解压到系统临时目录,代码中的__file__指向的是临时目录中的脚本文件,因此文本文件被创建在了临时目录中,而非执行可执行文件的当前目录,导致无法在预期位置看到文件。

解决方法

方法1:将文件写入当前工作目录

如果希望文件生成在执行可执行文件的当前目录,可改用os.getcwd()获取路径:

import os

def main():
    txtfile = os.path.join(os.getcwd(), 'text.txt')
    with open(txtfile, 'w') as f:
        for num in range(101):
            f.write(str(num) + '\n')

if __name__ == '__main__':
    main()
    print('script executed')

方法2:将文件写入可执行文件所在目录

如果希望文件和可执行文件同目录,可利用PyInstaller提供的sys._MEIPASS变量处理打包前后的路径差异:

import os
import sys

def get_resource_path(relative_path):
    try:
        # 打包后临时目录路径
        base_path = sys._MEIPASS
    except Exception:
        # 未打包时的脚本目录
        base_path = os.path.dirname(os.path.abspath(__file__))
    return os.path.join(base_path, relative_path)

def main():
    txtfile = get_resource_path('text.txt')
    with open(txtfile, 'w') as f:
        for num in range(101):
            f.write(str(num) + '\n')

if __name__ == '__main__':
    main()
    print('script executed')

内容的提问来源于stack exchange,提问作者dftag

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 05:15:36