3

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.

5
  • You can check if the file is empty first by using this function Then you can decide to read from the file all the information that is in it until non is left. Whatever information you read last is the last information entered and you can start your game from there. Remember to save everything back to the file before the user quits! Commented Aug 19, 2013 at 7:04
  • What do you mean by session Commented Aug 19, 2013 at 7:06
  • @Owen I think he is trying to create a game of some sorts therefore he will need to save the user's progress so that the user can start of where they left Commented Aug 19, 2013 at 7:10
  • @Owen What I mean by session is when the user executes the code, and changes variables, etc. Commented Aug 19, 2013 at 7:11
  • @Justin it isn't good solution to store states of your code, instead of this you should define which variables you need to store and choose in what way you will store them Commented Aug 19, 2013 at 7:58

3 Answers 3

1

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.
Sign up to request clarification or add additional context in comments.

8 Comments

How would I save all the other things too? I want to be able to continue from where I left off in a session.
@Justin You might also like to look at pickle, which can help add structures like lists and tuples to a file, for easy input/output
@Smac89 I still don't understand how to save the whole session into the text file. The link you gave me only tells me how to save one line. Also, the link to how to read the file is kind of confusing because I have no idea what any of those functions/commands those are. Could you explain? Thanks.
@Justin: The question is what do you mean when you want "to save the whole session". What are "all the other things too"?
@pepr I write some code, and a user executes it, using 'Run Module.' Then the code asks for input, such as name, age, etc. I want to save that information, and if the user quits, he/she can access from where he/she left off. Like a save point in a video game.
|
0

Going with @Justin's comment, here is how I would save and read the session each time:

import cPickle as pickle

def WriteProgress(filepath, progress):
    with open(filepath, 'w') as logger:
        pickle.dump(progress, logger)
        logger.close()

def GetProgress(filepath):
    with open(filepath, 'r') as logger:
        progress = pickle.load(logger)
        logger.close()
    return progress

WriteProgress('SaveSessionFile', {'name':'Nigel', 'age': 20, 'school': 'school name'})
print GetProgress('SaveSessionFile')

{'age': 20, 'name': 'Nigel', 'school': 'school name'}

This way, when you read the file again, you can have all the varaibles you declared before and start from where you left off.

Remember that since your program uses pickle module to read and write session information, tampering with the file after it has been written to can cause unforeseen outcomes; so be careful that it is only the program writing to and reading from that file

2 Comments

So I would have to put in individually all the variables I have? Also, I would like an explanation of what these defined functions do, etc. I like to know what I am writing so I can explain it and understand it.
Also, when I to put variables in the list I cannot, it asks for strings, which I guess is '', not bytes. How would I save the variables, in your explanation the 'name' is predefined as 'Nigel,' but my variables are user-inputted, therefore I cannot know what they are and predefine them.
0

You may be searching for a generalized mechanism that makes saving and restoring the wanted information somehow more easily. This is called persistence as the term in programming. However, it is not automatic. There are techniques how to implement it. The more complex and specific the implemented system is, the more specific the mechanism can be.

For simple cases, the explicit storing the data into a file is just fine. As Smac89 has shown in https://stackoverflow.com/a/18309156/1346705, the pickle module is a standard way how to save the status of whole Python objects. However, it is not neccessarily what you always need.

Update: The following code shows the principle. It should be enhanced for the real usage (i.e. should never be used this way, only in tutorial).

#!python3

fname = 'myfile.txt'

def saveInfo(fname, name, money):
    with open(fname, 'w', encoding='utf-8') as f:
        f.write('{}\n'.format(name))
        f.write('{}\n'.format(money))  # automatically converted to string

def loadInfo(fname):
    # WARNING: The code expect a fixed structure of the file.
    #   
    # This is just for tutorial. It should never be done this way
    # in production code.'''
    with open(fname, 'r', encoding='utf-8') as f:
        name = f.readline().rstrip()   # rstrip() is an easy way to remove \n
        money = int(f.readline())      # must be explicitly converted to int
    return name, money              


name = input('What is your name? ')
money = 5
print(name, money)

# Save it for future.
saveInfo(fname, name, money)

# Let's change it explicitly to see another content.
name = 'Nemo'
money = 100
print(name, money)

# Restore the original values.
name, money = loadInfo(fname)
print(name, money)

8 Comments

I have tried using the method indicated in that answer, however, I can only save strings, '', not variables(bytes). How would I save them?
What version of Python do you use?
I use the 3.3.1 version.
OK. What exactly do you mean by saving variables? In Python (and also in other languages), files can be open or in a text mode or in a binary mode. Python-3 strings can be directly saved only when the file is opened in the text mode with prescribed encoding (the default encoding is OS dependent). Or you have to encode the string explicitly and write it to the file opened in binary mode). Anyway, a stream of bytes is always written to the file -- independently on how it was opened.
I want to save an integer. I was using the wrong name. I cannot seem to save the integer, it keeps insisting on it having to be a string. I don't know about the text mode or binary mode, but my understanding of it is in IDLE, and by just clicking on the .py file which opens up the window command executor.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.