text file edit object

Skip Montanaro skip at pobox.com
Fri Jul 11 14:36:20 CEST 2003


    Facundo> myfile = open("foo.txt", "r")
    Facundo> mylines = myfile.readlines()[:-10]
    Facundo> myfile.writelines(mylines)
    Facundo> myfile.close()

    Facundo> I only see two problems with this:
    Facundo>    - Poor performance on very big files
    Facundo>    - Bad support on "hanging in the middle"

Not to mention the fact that you can't write to myfile as defined. ;-)  How
about something like (not tested):

    import os, sys

    try:
        infile = file("foo.txt", "r")
        lines = infile.readlines()[:-10]
        infile.close()
    except IOError:
        print >> sys.stderr, "edit failed"
    else:
        try:
            outfile = file("foo.txt.new", "w")
            outfile.writelines(lines)
            outfile.close()
        except IOError:
            try:
                os.unlink("foo.txt2")
            except IOError:
                pass
            print >> sys.stderr, "edit failed"
        else:
            os.rename("foo.txt2", "foo.txt")

?  On Windows I think you have to unlink foo.txt before calling os.rename().

Unfortunately, it quickly gets pretty baroque if you want to do things
right.  I'm not even sure IOError is the only exception that might be
raised.

Skip





More information about the Python-list mailing list