nn2 nn2 - 1 year ago 68
Python Question

Editing specific line in text file in python

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
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?

Answer Source

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'.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download