Fix Python – Editing specific line in text file in Python


Asked By – test

Let’s say I have a text file containing:


Is there a way I can edit a specific line in that text file? Right now I have this:

#!/usr/bin/env python
import io

myfile = open('stats.txt', 'r')
dan = myfile.readline()
print dan
print "Your name: " + dan.split('\n')[0]

    myfile = open('stats.txt', 'a')
except IOError:

Yes, I know that myfile.writelines('Mage')[1] is incorrect. But you get my point, right? I’m trying to edit line 2 by replacing Warrior with Mage. But can I even do that?

Now we will see solution for issue: Editing specific line in text file in Python


You want to do something like this:

# with is like your try .. finally block in this case
with open('stats.txt', 'r') as file:
    # read a list of lines into data
    data = file.readlines()

print data
print "Your name: " + data[0]

# now change the 2nd line, note that you have to add a newline
data[1] = 'Mage\n'

# and write everything back
with 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’.

This question is answered By – Jochen Ritzel

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0