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

问题描述

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

解决方法

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...