Overwrite single line of file

MRAB google at mrabarnett.plus.com
Fri Dec 5 14:15:11 EST 2008


chrispoliquin at gmail.com wrote:
> Hi,
> 
> I have about 900 text files (about 2 GB of data) and I need to make
> some very specific changes to the last line of each file.  I'm
> wondering if there is a way to just overwrite the last line of a file
> or replace the spots I want (I even know the position of the
> characters I need to replace).
> 
> I know how to open files and read the contents and then write
> everything out again after making the changes, but is there a way to
> replace just the last line without having to completely rewrite each
> file after making the changes?
> 
f = open(path, "r+")
f.seek(start_of_last_line)
f.write(new_line) # Assuming that new_line ends with "\n"
f.truncate() # In case the new line is shorter than what it's replacing
f.close()



More information about the Python-list mailing list