[Tutor] Truncate First Line of File
Bill Campbell
bill at celestial.net
Thu Feb 28 00:02:49 CET 2008
On Wed, Feb 27, 2008, Alex Ezell wrote:
>I must be missing some simple method on a file object or something.
>
>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.
>
>The only thing I can think to do is to readlines() and then slice off
>the first line in the resulting list, then writelines().
>
>pseduo-code:
>my_file = open('file.txt', 'wb')
>lines = my_file.readlines()
>del lines[0]
>my_file.writelines()
>my_file.close()
>
>Is there a better way?
Defensive programming avoids slurping entire files of unknown
size into memory. I would just open the file, use readline() to
get rid of the first line, the loop writing the rest.
If you're going to slurp the whole thing:
infile = open('inputfile')
lines = infile.readlines()
outfile = open('outfile', 'wb')
outfile.writelines(lines[1:])
outfile.close()
Another way on *nix systems that might be better wouldn't use
python at all. Edit the file in place with ed or ex:
#!/bin/sh
ex - filename <<DONE
1d
w
q
DONE
Bill
--
INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC
URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way
FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676
Government is actually the worst failure of civilized man. There has
never been a really good one, and even those that are most tolerable
are arbitrary, cruel, grasping and unintelligent. -- H. L. Mencken
More information about the Tutor
mailing list