How to load file and create infinite save files?

So, I'm creating a little game in python to learn more about this language and I have two questions:

First - There is a way to every time that the player click on the 'new game', the program create a new save file?

Second - How can I load the saved files? They are text files and I don't know how to load them. The things that will be saved are the number coins, health, the name of the character, and other things. And the player can choice which file he want to load?

Thanks for the attention.

Upvotes: 1

Views: 323

Answers (1)

en_Knight
en_Knight

Reputation: 5381

Saving is easy. You have many options, but two of the primary ones are:

1) The pickle module

https://docs.python.org/2/library/pickle.html

Built (by default, in Python3x) on C code, this is a very fast way to serialize objects and recover them. Use unique names for files, and look at the "dump" and "load" methods.

From the docs, this example should get you started:

# Save a dictionary into a pickle file.
import pickle

favorite_color = { "lion": "yellow", "kitty": "red" }

pickle.dump( favorite_color, open( "save.p", "wb" ) )

# Load the dictionary back from the pickle file.

favorite_color = pickle.load( open( "save.p", "rb" ) )
# favorite_color is now { "lion": "yellow", "kitty": "red" }

In tkinter, this (the tkFileDialog)

http://tkinter.unpythonic.net/wiki/tkFileDialog

Should help you make a dialog for selecting file locations. Here's a good example of its usage:

Opening File (Tkinter)

2) Load/save and parse files yourself

You said that your game is for learning purposes, so doing things through manual file io isn't a bad idea. The documentation has a good place to get started, using "open" as the primary function for handling files. Again, "infinite" files simply means using unique name for each one

https://docs.python.org/2/tutorial/inputoutput.html

An example of manual io is

# writing data to a file
favorite_colors = {'tim':'yellow','mary':'blue'}

newsave_file = open(filename,'w')
for key, val in favorite_colors.items():
    newsave_file.write(str(key)+'|'+str(val)+'\n')

newsave_file.close()

# reading data from a file
favorite_colors = {}
open_file = open(filename,'r')
for line in open_file:
    pair = line.split('|')
    favorite_colors[pair[0]] = pair[1]
open_file.close()

You may want to do things like using try/catch block to ensure the program doesn't crash, or a more sophisticated parser technique. That's all up to you!

Upvotes: 2

Related Questions