【发布时间】:2020-12-01 03:38:05
【问题描述】:
如何保存用户的输入并在重新启动程序时询问他们是否要再次使用它,这样他们就不必每次关闭程序时都输入相同的内容?
【问题讨论】:
标签: python python-3.x authentication input passwords
如何保存用户的输入并在重新启动程序时询问他们是否要再次使用它,这样他们就不必每次关闭程序时都输入相同的内容?
【问题讨论】:
标签: python python-3.x authentication input passwords
你可以使用这样的东西。它将用户输入数据保存到config.py模块,所以你可以在任何地方使用它。
import os
user_input = None
if os.path.exists('config.py'): #check if config file exist
ask = input("Do you want use previous data? (yes/no)")
if ask == 'no':
user_input = input("Some things...")
elif ask == 'yes':
import config
user_input = config.last_input # take last value of input from config file
else:
print("Wrong command, please anserw yes or no.")
else:
user_input = input("Some things...")
print(user_input)
# save input
with open("config.py", "w+") as file:
file.write(f"last_input = {user_input}")
方法很简单,不需要使用 json 或 ini 文件。您只需复制并粘贴此内容即可。
【讨论】:
您应该将数据存储在一些DB或JSON文件中,关闭程序后无法保存存储在变量中的输入数据。
【讨论】:
open、write_in_json ... 如果您打算使用一些 DB SQLi 是最轻量级且更适合用于小数据的SQLiPython .. 对于更复杂的数据存储,您应该使用Postgres