Editing specific line in text file in Python
You want to do something like this:
# with is like your try .. finally block in this casewith open('stats.txt', 'r') as file: # read a list of lines into data data = file.readlines()print dataprint "Your name: " + data[0]# now change the 2nd line, note that you have to add a newlinedata[1] = 'Mage\n'# and write everything backwith open('stats.txt', 'w') as file: file.writelines( data )
The reason for this is that you can't do something like "change line 2" directly in a file. You can only overwrite (not delete) parts of a file - that means that the new content just covers the old content. So, if you wrote 'Mage' over line 2, the resulting line would be 'Mageior'.