Reputation: 672
I have a python game that writes user data like this: Bob 3
on to at text file. I'm trying to code so if a player reaches a certain point it will delete the level number (in the example: 1
) and write the new level. I have split the line with this:
name, level = line.split()
Is there any to do this?
Upvotes: 0
Views: 96
Reputation: 77952
"updating" a plain file really mean writing a new file then replace the old one with the new one - you cannot just do an "inplace" update. While technically possible and not really difficult it might not be the most efficient solution for your needs, since you'll have to go thru the whole read + parse old file / write the new one / rename for each update (and possibly have to deal with concurrent access too depending on your application). Using some kind of database (key/value, relational, document, whatever...) would probably be a better solution, since it will take care of most of the housekeeping.
For a very naive answer to your question, it would look like this:
def update_level(username, new_level):
inpath = "/path/to/your/file"
outpath = "path/to/tmpfile"
with open(inpath) as infile:
with open(outpath, "w") as outfile:
for line in infile:
line = line.strip()
name, level = line.split()
if name == username:
line = " ".join((username, new_level))
outfile.write("%s\n" % line)
os.rename(outpath, inpath)
Upvotes: 1