gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:04:42 24 4
gpt4 key购买 nike

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

例子,第一次打开程序:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com