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.

Justin
  • 283
  • 2
  • 5
  • 11
  • You can check if the file is empty first by using [this function](http://stackoverflow.com/questions/2507808/python-how-to-check-file-empty-or-not/15926220#15926220) 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! – smac89 Aug 19 '13 at 07:04
  • What do you mean by session – Owen Aug 19 '13 at 07: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 – smac89 Aug 19 '13 at 07:10
  • @Owen What I mean by session is when the user executes the code, and changes variables, etc. – Justin Aug 19 '13 at 07: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 – Volodymyr Pavlenko Aug 19 '13 at 07:58

3 Answers3

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.
TerryA
  • 58,805
  • 11
  • 114
  • 143
  • 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 Aug 19 '13 at 07:03
  • 1
    @Justin You might also like to look at [pickle](http://docs.python.org/2/library/pickle.html), which can help add structures like lists and tuples to a file, for easy input/output – TerryA Aug 19 '13 at 07:12
  • @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 Aug 19 '13 at 07:36
  • @Justin: The question is what do you mean when you want *"to save the whole session"*. What are *"all the other things too"*? – pepr Aug 19 '13 at 08:20
  • @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. – Justin Aug 19 '13 at 19:44
  • @Justin: Haidro have shown how to do that. There is no magic in programming in the sense *"save everything that may need in future"*. One has to be explicit. If you need to save three pieces of the information, you have to save three of them. – pepr Aug 20 '13 at 05:51
  • I am trying to save an integer into the file, but it does not let me. Only strings are allowed. – Justin Aug 20 '13 at 06:16
  • @Justin then do `str(number)` to convert it to a string. Then `int(number)` to turn it back – TerryA Aug 20 '13 at 07:34
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

smac89
  • 39,374
  • 15
  • 132
  • 179
  • 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. – Justin Aug 19 '13 at 19:45
  • 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. – Justin Aug 19 '13 at 20:08
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)
Community
  • 1
  • 1
pepr
  • 20,112
  • 15
  • 76
  • 139
  • I have tried using the method indicated in that answer, however, I can only save strings, '', not variables(bytes). How would I save them? – Justin Aug 20 '13 at 06:03
  • What version of Python do you use? – pepr Aug 20 '13 at 06:34
  • I use the 3.3.1 version. – Justin Aug 20 '13 at 06:55
  • 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. – pepr Aug 20 '13 at 07:19
  • 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. – Justin Aug 20 '13 at 07:24
  • Try the code from the updated answer, study it, and ask for details ;) – pepr Aug 20 '13 at 07:52
  • What does 'The code expects a fixed structure of the file' mean? – Justin Aug 21 '13 at 02:25
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/35893/discussion-between-pepr-and-justin) – pepr Aug 21 '13 at 08:44