[Tutor] Truncate First Line of File

Alex Ezell aezell at gmail.com
Thu Feb 28 00:12:18 CET 2008


On Wed, Feb 27, 2008 at 5:01 PM, Kent Johnson <kent37 at tds.net> wrote:
>
> 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.

Oops, forgot to send this to the list before:

Thanks Kent and Bill. I typed that out really quickly, hence the "pseudo-code"
disclaimer. I know it wasn't pseudo enough :)

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.

Of course, it's not Python ;) and it'd be cool to know a Python way to do it.

Thanks again for the help.

/alex


More information about the Tutor mailing list