I want my code to save information so the next time i run the code it will be remembering the information we gave it earlier
Question:
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..
Answers:
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')
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}")
I’ve just had a look around and found the sqlitedict
package that seems to make this sort of thing easy.
from sqlitedict import SqliteDict
def main() -> None:
prefs = SqliteDict("prefs.sqlite")
# try getting the user's name
if name := prefs.get("name"):
# got a name, see if they want to change it
if newname := input(f"Enter your name [{name}]: ").strip():
name = newname
else:
# keep going until we get something
while not (name := input("Enter your name: ").strip()):
pass
print(name)
# save it for next time
prefs["name"] = name
prefs.commit()
if __name__ == "__main__":
main()
Note that I’m using Python 3.8’s new "Walrus operator", :=
, to make the code more concise.
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..
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')
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}")
I’ve just had a look around and found the sqlitedict
package that seems to make this sort of thing easy.
from sqlitedict import SqliteDict
def main() -> None:
prefs = SqliteDict("prefs.sqlite")
# try getting the user's name
if name := prefs.get("name"):
# got a name, see if they want to change it
if newname := input(f"Enter your name [{name}]: ").strip():
name = newname
else:
# keep going until we get something
while not (name := input("Enter your name: ").strip()):
pass
print(name)
# save it for next time
prefs["name"] = name
prefs.commit()
if __name__ == "__main__":
main()
Note that I’m using Python 3.8’s new "Walrus operator", :=
, to make the code more concise.