text file edit object

Discussion in 'Python' started by Simon Burton, Jul 11, 2003.

  1. Simon Burton

    Simon Burton Guest

    # Needed to edit a text file like a list:

    file = TextFile( "foo.txt" )
    del file[:-10] # remove last 10 lines
    file.save()

    # Ended up writing this:

    #!/usr/bin/env python

    from tempfile import mktemp
    import shutil
    import sys

    class TextFile(list):
    def __init__(self,name):
    file = open( name )
    self[:] = file.readlines()
    self.name = name
    def save(self):
    temp = mktemp()
    file = open( temp, "w" )
    file.writelines( self )
    file.close()
    #tgt = "_"+self.name
    tgt = self.name
    #print temp, tgt
    shutil.copy( temp, tgt )


    # Is there Another Way?

    # Simon Burton.
    Simon Burton, Jul 11, 2003
    #1
    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. San Diego Guy
    Replies:
    0
    Views:
    544
    San Diego Guy
    Aug 7, 2003
  2. Schultz
    Replies:
    3
    Views:
    555
    =?Utf-8?B?QmlsbCBCb3Jn?=
    Feb 14, 2005
  3. =?Utf-8?B?a2Vu?=
    Replies:
    1
    Views:
    10,325
    Wiktor Zychla [C# MVP]
    Jan 23, 2006
  4. Simon Burton

    text file edit object?

    Simon Burton, Feb 23, 2004, in forum: Python
    Replies:
    1
    Views:
    256
    Simon Burton
    Feb 23, 2004
  5. Sharon McCarty
    Replies:
    0
    Views:
    248
    Sharon McCarty
    Nov 24, 2004
Loading...

Share This Page