[Tutor] Truncate First Line of File
Kent Johnson
kent37 at tds.net
Thu Feb 28 00:01:11 CET 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?
No, you have to rewrite the file, that is the way the filesystem works.
Your code above is pretty buggy though, you should at least
open file for read
readlines
close file
open file for write
writelines
close file
Even safer is to write to a new file, then rename. The fileinput module
makes it convenient to safely overwrite a file with a new one.
Kent
More information about the Tutor
mailing list