Simple questions about txt file input and output with Python 2.6
this is my first post here to stackoverflow, and I am still just learning Python and programming in general. I'm working on some simple game logic, and I'm getting a little washed up on how Python handles file input/output.
What I'm trying to do is, while my game is running, store a series of variables (all numeric, integer data), and when the game is over, dump that information to txt file that can later be read (again, as numeric, integer data) so that it can be added to. A tracker, really. Perhaps if you were playing some racing game, for example, every time you hit a pedestrian, pedestrians += 1. Then when your game is over, after hitting like 23 pedestrians, that number (along with any other variables I wished to开发者_如何学Python track) is saved to a text file. When you start the game again, it loads the number 23 back into the pedestrians variable, so if you hit 30 more this time you end up with 53 total, and so on. Thanks in advance!Does it have to be text? I'd use pickle if not
http://docs.python.org/library/pickle.html
There are quite a few ways to do this. Do you want the file to be human-readable or human-writable? (Could encourage cheating if you do.)
The simplest thing that you could do which would work is to use the ConfigParser library, which stores simple data like what you described in a text file. Something like:
Reading:
import ConfigParser
config = ConfigParser.ConfigParser()
config.readfp(open('game_data.dat'))
dead_pedestrians = config.getint('JoeUser', 'dead_pedestrians')
Writing:
config = ConfigParser.RawConfigParser()
config.add_section('JoeUser')
config.set('JoeUser', 'dead_pedestrians', '15')
with open('game_data.dat', 'wb') as configfile:
config.write(configfile)
Other options: If you don't want it to be human-readable, you could use shelve (but a clever user who knows you're using python would find it trivial to read.
Hope that helps!
精彩评论