Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save session data (Python)

Tags:

python

Say there is some code I wrote, and someone else uses, and inputs their name, and does other stuff the code has.

name = input('What is your name? ')
money = 5
#There is more stuff, but this is just an example.

How would I be able to save that information, say, to a text file to be recalled at a later time to continue in that session. Like a save point in a video game.

like image 869
Justin Avatar asked Mar 07 '26 18:03

Justin


1 Answers

You can write the information to a text file. For example:

mytext.txt

(empty)

myfile.py

name = input('What is your name? ')
... 
with open('mytext.txt', 'w') as mytextfile:
    mytextfile.write(name)
    # Now mytext.txt will contain the name.

Then to access it again:

with open('mytext.txt') as mytextfile:
    the_original_name = mytextfile.read()

print the_original_name
# Whatever name was inputted will be printed.
like image 95
TerryA Avatar answered Mar 09 '26 08:03

TerryA