Changing a line in a text file

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • kah

    Changing a line in a text file

    How do I change a line in a file??

    For example I have the follwing text in my file:

    line1
    line2
    line3
    line4

    How do I replace 'line2' with 'newline'. Since the write operation in
    python will overwrite everything.

    Regards,
    Kah

  • Michael Hoffman

    #2
    Re: Changing a line in a text file

    kah wrote:[color=blue]
    > How do I change a line in a file??
    >
    > For example I have the follwing text in my file:
    >
    > line1
    > line2
    > line3
    > line4
    >
    > How do I replace 'line2' with 'newline'. Since the write operation in
    > python will overwrite everything.[/color]

    This is the best I can figure out what you mean:

    lines = []
    for line in file("myfile.tx t"):
    if line == "line2\n":
    line = "newline\n"
    lines.append(li ne)

    file("myfile.tx t", "W").writelines (lines)

    --
    Michael Hoffman

    Comment

    • kah

      #3
      Re: Changing a line in a text file

      Hi,

      the example provided by Vishnu is quite close to what I want but it
      still required me to write all the data back to the file.

      Is there any way where I can just write a particular line?

      Regards,
      Kah

      Comment

      • Steve Holden

        #4
        Re: Changing a line in a text file

        kah wrote:[color=blue]
        > Hi,
        >
        > the example provided by Vishnu is quite close to what I want but it
        > still required me to write all the data back to the file.
        >
        > Is there any way where I can just write a particular line?
        >[/color]
        If you are asking whether you can update a file in place, the answer is
        "yes" - look up "lseek" in the Python documentation (module os, under
        "File Descriptor Operations".

        However, you asked about replacing one line with another of a different
        length: since this will mean changing the offsets of all subsequent
        bytes you have no way to do this other than writing out the whole
        content of the file following the modification. You would also have to
        ensure that you truncated the file to the correct length.

        In general, although they don't make it obvious that they are doing so
        most programs that "change" files (text editors and the like) are really
        writing new copies.

        regards
        Steve
        --
        Steve Holden +1 703 861 4237 +1 800 494 3119
        Holden Web LLC http://www.holdenweb.com/
        Python Web Programming http://pydish.holdenweb.com/

        Comment

        • Miki Tebeka

          #5
          Re: Changing a line in a text file

          Hello kah,
          [color=blue]
          > How do I change a line in a file??
          >
          > For example I have the follwing text in my file:
          >
          > line1
          > line2
          > line3
          > line4
          >
          > How do I replace 'line2' with 'newline'. Since the write operation in
          > python will overwrite everything.[/color]
          See http://docs.python.org/lib/module-fileinput.html (inplace=1 is what you
          want).

          Bye.
          --
          ------------------------------------------------------------------------
          Miki Tebeka <miki.tebeka@zo ran.com>

          The only difference between children and adults is the price of the toys

          -----BEGIN PGP SIGNATURE-----
          Version: GnuPG v1.4.0 (Cygwin)

          iD8DBQFCbNAB8jA dENsUuJsRAtc+AJ 9cYXBpu4MZ+4NIX Fy0MsdISmpRRwCg thFp
          6HB7zB6lq9dpMbz +bZgRtkY=
          =dRnr
          -----END PGP SIGNATURE-----

          Comment

          • Larry Bates

            #6
            Re: Changing a line in a text file

            You might be able to use "edge" case to make this simple.

            1) If the line you are replacing is unique in the file

            and

            2) File can easily fit in memory

            you can write:

            fp=open(filenam e, 'r')
            contents=fp.rea d()
            fp.close()
            newcontents=new line.join(conte nts.split(line2 ))
            fp=open(filenam e, 'w')
            fp.write(newcon tents)
            fp.close()

            For small files this is very efficient.

            Larry Bates


            kah wrote:[color=blue]
            > How do I change a line in a file??
            >
            > For example I have the follwing text in my file:
            >
            > line1
            > line2
            > line3
            > line4
            >
            > How do I replace 'line2' with 'newline'. Since the write operation in
            > python will overwrite everything.
            >
            > Regards,
            > Kah
            >[/color]

            Comment

            • Kirk Job Sluder

              #7
              Re: Changing a line in a text file

              Steve Holden <steve@holdenwe b.com> writes:
              [color=blue]
              > kah wrote:
              > However, you asked about replacing one line with another of a
              > different length: since this will mean changing the offsets of all
              > subsequent bytes you have no way to do this other than writing out the
              > whole content of the file following the modification. You would also
              > have to ensure that you truncated the file to the correct length.
              >
              > In general, although they don't make it obvious that they are doing so
              > most programs that "change" files (text editors and the like) are
              > really writing new copies.[/color]

              In addition, I would argue that editing a file in place using a
              non-interactive program is dangerous and bad practice in general. By
              the time you find a bug in your edit script, the original is lost. This
              is something I learned from bitter experience when I tried to be smart
              and make script-based edits over entire directories of html files.

              In unix shell scripting idiom, I would do something like:

              mv file file.bak
              sed -e 'g/oldline/c newline' < file.bak > file

              And yes, I know that some versions of sed have the --in-place option.

              Then, I would check for side effects:

              diff file file.bak

              All of this can be done in python, however I'm not overly familiar with
              difflib and it seems to require both versions of the file in memory. So
              an external diff might be better.

              import os
              os.rename(foo,f oo.bak)
              infile = open(foo.bak,'r ')
              outfile = open(foo,'w')
              for line infile:
              #test and substitution code block
              outfile.write(l ine)

              Using separate input and output files also has the advantage of being
              memory efficient.


              [color=blue]
              >
              > regards
              > Steve
              > --
              > Steve Holden +1 703 861 4237 +1 800 494 3119
              > Holden Web LLC http://www.holdenweb.com/
              > Python Web Programming http://pydish.holdenweb.com/
              >[/color]

              --
              Kirk Job-Sluder
              "The square-jawed homunculi of Tommy Hilfinger ads make every day an
              existential holocaust." --Scary Go Round

              Comment

              • Simon Brunning

                #8
                Re: Changing a line in a text file

                On 4/25/05, Kirk Job Sluder <kirk@jobsluder .net> wrote:[color=blue]
                > In addition, I would argue that editing a file in place using a
                > non-interactive program is dangerous and bad practice in general. By
                > the time you find a bug in your edit script, the original is lost. This
                > is something I learned from bitter experience when I tried to be smart
                > and make script-based edits over entire directories of html files.[/color]

                See http://aspn.activestate.com/ASPN/Coo...n/Recipe/56037

                --
                Cheers,
                Simon B,
                simon@brunningo nline.net,

                Comment

                Working...