如何从需要读取和写入单独文件夹中的.txt文件的.py文件创建python可执行文件

时间:2019-12-01 16:49:38

标签: python directory pyinstaller

我创建了一个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脚本和“ encrypted passwords”文件夹位于同一文件夹中,当我运行它时没有任何问题。

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

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

1 个答案:

答案 0 :(得分:0)

您可以检查文件夹是否存在,并仅在不存在的情况下创建文件夹

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)