[Tutor] Truncate First Line of File

Alan Gauld alan.gauld at btinternet.com
Thu Feb 28 01:39:58 CET 2008


"Alex Ezell" <aezell at gmail.com> wrote

>>  > What I need to do is to truncate the first line of a file which 
>> has an
>>  > unknown number of lines and an unknown size.

> I might do something like this:
> os.system("sed -i '1d' %s" % filename)
>
> I suspect it will be much faster on large files, but I haven't 
> tested that yet.

It might be a bit faster since sed is written in C, but then so is
Pythons file handling code. What sed doesn't do is anything
different to what Pyhon does, it still reads the file in and back
out again.

One slightly faster way of doing it is (in pseudo code):

f = open(filena,me,'r')
f.readline() # lose first line
s = f.read()  # get the rest as a string
f.close()
f = open(filename,'w')
f.write(s)
f.close()

which avoids all the line splitting/list creation of readlines()

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
Temorarily at:
http://uk.geocities.com/alan.gauld@btinternet.com/
Normally:
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list