首页 > 解决方案 > 保存输入并在重新启动程序时要求再次使用它

问题描述

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

标签: pythonpython-3.xauthenticationinputpasswords

解决方案


你可以使用这样的东西。它将用户输入数据保存到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 文件。你可以复制粘贴这个,就可以了。


推荐阅读