保存输入,并要求重新启动程序时再次使用它

问题描述

如何保存用户的输入并询问他们是否在重新启动程序时再次使用它,这样他们不必在每次关闭程序时都输入相同的内容

解决方法

您应该将数据存储在某些 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文件。您只需复制并粘贴此文件即可。