Save input and ask to use it again when restarting program

Viewed 157

How can I save a user's input and ask them if they want to use it again when restarting the program, so they don't have to enter the same thing every time they close the program?

2 Answers

You should store the data in some DB or JSON file, there is no way to save input data stored in a variable after closing the program.

You can use something like this. It's save user input data to config.py module, so you can use it anywhere.

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}")

It's easy way, not needed to use json or ini files. You can just copy&paste this, will work.

Related