Editing specific line in text file in Python Editing specific line in text file in Python python python

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


def replace_line(file_name, line_num, text):    lines = open(file_name, 'r').readlines()    lines[line_num] = text    out = open(file_name, 'w')    out.writelines(lines)    out.close()

And then:

replace_line('stats.txt', 0, 'Mage')


you can use fileinput to do in place editing

import fileinputfor  line in fileinput.FileInput("myfile", inplace=1):    if line .....:         print line