首页 > 解决方案 > 如何从需要在单独文件夹中读取和写入 .txt 文件的 .py 文件创建 python 可执行文件

问题描述

我创建了一个 python gui,它可以将有关用户编写 .txt 文件的信息存储在一个名为加密密码的单独文件夹中。所以它有像

file = open(file='encrypted passwords\\first password.txt', mode='w')
file.write('123456')
file.close()

password = open(file=('encrypted passwords\\first password.txt'), mode='r').read()

os.unlink('encrypted passwords\\first password.txt')

python脚本和“加密密码”文件夹在同一个文件夹中,当我运行它时没有问题。

但是当我使用 pyinstaller 创建 .exe 文件时,它不起作用,因为它没有“加密密码”文件夹!

如果我手动添加了“加密密码”文件夹,它可以工作,但有没有办法不手动添加文件夹?

标签: pythondirectorypyinstaller

解决方案


您可以检查文件夹是否存在并仅在它不存在时才创建它

import os

if not os.path.exists('encrypted passwords'):
    os.makedirs('encrypted passwords')

在较新的 Python 中,您可以使用exist_ok=True在文件夹存在时跳过

import os

os.makedirs('encrypted passwords', exist_ok=True)

推荐阅读