stophers
stophers

Reputation: 23

Appending a text file

I'm teaching myself how to program and am currently using Python 3.3. I'm trying to append a text file. Currently, the text file looks like:

117: 5.21|8.50|10.0|3.42

This text is keeping track of ratings. So ITEM_A has been rated 117 times, characteristic 1 has an average rating of 5.21, characteristic 2 has an average rating of 8.50, characteristic 3 has an average rating of 10.0 and so on...

I wish to be able to update these. So if I wish to rate ITEM_A again, 117 changes to 118, and the scores 4.20|7.50|6.33|9.05 will also change to reflect the updated averages.

I thought I could do this while in the append/read access mode ('a+') using a combination of tell(), seek() and write(). However, I seem to only be able to write to the end of my file. Am I barking up the wrong tree, or is my code just incorrect?

test_file = 'example.txt'           #Current:   117: 5.21|8.50|10.0|3.42
file = open(test_file, 'a+')

file.seek(0, 0)
file.write('118')                    #I want:   118: 5.21|8.50|10.0|3.42

file.close()

Upvotes: 2

Views: 281

Answers (1)

thebjorn
thebjorn

Reputation: 27311

The docs (http://docs.python.org/3.3/library/functions.html#open) say that

'a' is for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position).

I think you want the 'r+' mode..?

Upvotes: 1

Related Questions