[英]Save input and ask to use it again when restarting program
如何保存用戶的輸入並在重新啟動程序時詢問他們是否要再次使用它,這樣他們每次關閉程序時都不必輸入相同的內容?
您應該將數據存儲在某些DB或JSON文件中,關閉程序后無法保存存儲在變量中的輸入數據。
你可以使用這樣的東西。 它將用戶輸入數據保存到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 文件。 你可以復制粘貼這個,就可以了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.