python - 如何只在第一次打开程序时保存一个目录

标签 python python-3.x

我正在尝试编写一个将加密密码保存在文件中的程序,但我想要在首次使用该程序时输入目录的选项,以便它知道将密码保存在何处。有谁知道我怎样才能做到这一点?

例子,第一次打开程序:

dir = input("What directory would you like to use to save your passwords?")
file_name = dir+"\\passwords.txt"   
open(file_name, "w")   # creates the file
# runs the rest of the program or exits

然后,在第一次运行程序之后,它只是跳过这部分。

最佳答案

您必须将密码文件的位置保存在某处,您可以尝试在用户主目录中创建一个配置文件。

应用启动时,执行以下操作:

from os.path import expanduser, join, exists
home = expanduser("~")

if not exists(join(home, '.my-config')):
     # ask for password file path
     ...
     # persist path
     with open(join(home, '.my-config', 'w')) as config_file:
           config_file.write(password_file_path)
else:
    # read the password file path from the config
    with open(join(home, '.my-config', 'r')) as config_file:
           password_file_path=config_file.read()

 # continue with code
 ...

为了使配置文件更有用,例如,您可以创建一个包含所有所需数据的字典,并将一个 json 字符串保存到配置文件中,以便您稍后可以将该字典读回应用程序。

关于python - 如何只在第一次打开程序时保存一个目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41640748/

相关文章:

python - 在配置表中按行保存数据与在 Postgres JSONField 中保存为键——哪个更好?

string - Python 3 中如何在字节和字符串之间进行转换?

python - 类型错误 : 'Index' object is not callable and SyntaxError: invalid syntax

python - 基于索引列表返回子列表的最简单和最有效的函数是什么?

python - 每组增量变量

Python 3 在划分两个大数时给出错误的输出?

python - Tensorflow API Ubuntu 错误

python-3.x - 从 Azure Datalake 下载时是否可以设置 block 大小?

python - 检索选定的记录

python - 在 Windows 上编译 scikit-image 来运行测试