简体   繁体   English

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

[英]How to create python executable from a .py file that need to read and write .txt files in a separate folder

I've created a python gui that can store information about the user writing .txt files in a separate folder named encrypted passwords.我创建了一个 python gui,可以将有关用户写入 .txt 文件的信息存储在名为加密密码的单独文件夹中。 So it has lines like所以它有像

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

and

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

and

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

The python script and the 'encrypted passwords' folder are in the same folder and when I run it get no problems. python 脚本和“加密密码”文件夹在同一个文件夹中,当我运行它时没有问题。

But when I have created the .exe file using pyinstaller it did not work because it had no 'encrypted passwords' folder!但是当我使用 pyinstaller 创建 .exe 文件时它不起作用,因为它没有“加密密码”文件夹!

If I added manually a 'encrypted passwords' folder it worked but is there a way in order to not manually add the folder?如果我手动添加了一个“加密密码”文件夹,它会起作用,但是有没有办法不手动添加文件夹?

You can check if folder exists and create it only if it not exists您可以检查文件夹是否存在并仅在它不存在时创建它

import os

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

In newer Python you can use exist_ok=True to skip when folder exists在较新的 Python 中,您可以使用exist_ok=True在文件夹存在时跳过

import os

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 python从文件夹中读取所有文件,并将文件名和其他信息写入txt文件 - python read all files from a folder and write the file name and other info into a txt file 如何读取文件夹中的多个.txt 文件并使用 python 写入单个文件? - How to read multiple .txt files in a folder and write into a single file using python? 如何依次读取两个txt文件并将其写入python中的新文件? - how to sequentially read two txt files and write into a new file in python? 如何使用 python 程序从这个文本文件中读取正确的行,然后通过填写从 .txt 文件中提取的数据来创建一个 .py 文件? - How read the correct lines from this text file with a python program, and then create a .py file by filling in the data extracted from the .txt file? 如何在python中读取文件夹中的txt文件列表 - how to read a list of txt files in a folder in python Python - 从文件夹读取文件并以格式写入 CSV 文件 - Python - Read files from folder and Write CSV file in format 如何使用 Python 将文件夹中的 all.txt 文件和 append 其内容读取到 one.txt 文件中? - How to read all .txt files in a folder and append its contents into one .txt file, using Python? 如何将从 txt 文件中选择的文件复制到另一个文件夹 python - How to copy files selected from a txt file to another folder python 从一个巨大的 txt 文件中解析并将每个 output 写入单独的文件中 - parse from a huge txt file and write each output in separate files 如何在具有不同名称的文件夹中加载 all.txt 文件 - Python - How to load all .txt files in a folder with separate names - Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM