Overwrite single line of file

C

chrispoliquin

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?

-Chris
 
M

MRAB

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()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top