Home > other >  I want my code to save information so the next time i run the code it will be remembering the inform
I want my code to save information so the next time i run the code it will be remembering the inform

Time:10-05

I want my code to save information..

for example in here we take a input of what is my name :

your_name = str(input("What is your name : "))

then if i stop the code and run it again i want it to still know my name

but the problem is that when you stop the code everything gets deleted and the program doesn't know what is your name since you stopped the code..

CodePudding user response:

That's how programs work. If you want to persist anything, you can store the information to file and load the information from file the every time the program runs.

For example,

import os

filepath = 'saved_data.txt'

try:
    # try loading from file
    with open(filepath, 'r') as f:
        your_name = f.read()
except FileNotFoundError:
    # if failed, ask user
    your_name = str(input("What is your name : "))
    # store result
    with open(filepath, 'w') as f:
        f.write(your_name)

With more complex data, you will want to use the pickle package.

import os
import pickle

filepath = 'saved_data.pkl'

try:
    # try loading from file
    with open(filepath, 'r') as f:
        your_name = pickle.load(f)
except FileNotFoundError:
    # if failed, ask user
    your_name = str(input("What is your name : "))
    # store result
    with open(filepath, 'w') as f:
        pickle.dump(your_name)

To be able to dump and load all the data from your session, you can use the dill package:

import dill

# load all the variables from last session
dill.load_session('data.pkl')

# ... do stuff

# dump the current session to file to be used next time.
dill.dump_session('data.pkl')

CodePudding user response:

You'll need to rely on a database (like SQLite3, MySQL, etc) if you want to save the state of your program.

You could also writing to the same file you're running and append a variable to the top of the file as well--but that would cause security concerns if this were a real program since this is equivalent to eval():

saved_name = None
if not saved_name:
    saved_name = str(input("What is your name : "))
    with open("test.py", "r") as this_file:
        lines = this_file.readlines()
        lines[0] = f'saved_name = "{saved_name}"\n'
        with open("test.py", "w") as updated_file:
            for line in lines:
                updated_file.write(line)
print(f"Hello {saved_name}")
  • Related