text file edit object

Simon Burton simonb at webone.com.au
Fri Jul 11 02:49:27 EDT 2003


# 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.





More information about the Python-list mailing list