Overwrite single line of file

Discussion in 'Python' started by chrispoliquin@gmail.com, Dec 5, 2008.

  1. Guest

    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
     
    , Dec 5, 2008
    #1
    1. Advertising

  2. MRAB Guest

    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()
     
    MRAB, Dec 5, 2008
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Hugo
    Replies:
    10
    Views:
    1,343
    Matt Humphrey
    Oct 18, 2004
  2. Matt@revera
    Replies:
    4
    Views:
    323
    Erik Max Francis
    Apr 7, 2005
  3. scad
    Replies:
    23
    Views:
    1,192
    Alf P. Steinbach
    May 17, 2009
  4. Raymond O'connor

    puts overwrite line

    Raymond O'connor, Dec 7, 2006, in forum: Ruby
    Replies:
    3
    Views:
    117
    Raymond O'connor
    Dec 7, 2006
  5. ela
    Replies:
    12
    Views:
    363
    Uri Guttman
    Apr 6, 2009
Loading...

Share This Page