python - 如何从需要在单独文件夹中读取和写入 .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 文件时,它不起作用,因为它没有“加密密码”文件夹!
如果我手动添加了“加密密码”文件夹,它可以工作,但有没有办法不手动添加文件夹?
解决方案
您可以检查文件夹是否存在并仅在它不存在时才创建它
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)
推荐阅读
- node.js - 意外的错误消息
- php - Silverstripe 在导出 CSV 文件时抛出错误 500
- scala - Scala:一次映射和解压缩列表
- git - 如何在 jupyter notebook 中添加 github 图标
- javascript - 加载文件夹内容
- tfs - 在 TFS 2018 中的 Visual Studio 构建任务期间指定 DesktopPackageLocation 中的项目名称
- javascript - ES6 将组件包装在组件内
- jquery - 递归使用 jQuery .append()
- javascript - 创建用户在firebase中创建具有相同信息的身份不明的孩子
- c++ - 使用 FreeType 和 SDL2 渲染文本会生成白色方块而不是字符