newbie Q: delete list few lines in file

Neil Schemenauer nas at python.ca
Sat Jun 29 19:52:21 EDT 2002


Xah Lee wrote:
> i have a folder full of individual email text file, whose ending may
> be the following:
> 
> _______________________________________________
> some mailing list
> some at list.com
> http://some.com/ttt
> 
> I want to delete them, but only if they are the last few lines in the
> file.

I would use something like the following untested code:

    import os

    marker = ('some mailing list\n'
              'some at list.com\n'
              'http://some.com/ttt\n')
    for filename in os.listdir(sys.argv[1]):
        f = open(filename)
        f.seek(-1000, 2)
        tail = f.read()
        if tail.find(marker) >= 0:
            os.unlink(filename)

The seek() call is only necessary if you're dealing with really large
files.  If you know the files are all pretty small and the script is a
"one off job" then you could leave it out and read the whole file into
memory.  

> * how to write to file inplace? (or, do i write to a new file, then
> delete original, and rename the new file?)

You need to open the file using the 'r+' or 'a+' flag.

> * as far as a newbie, i use "xreadlines" module. I wasn't able to get
> the total number of lines in a file.
> li=xreadlines.xreadlines(f)
> num=len(li)
> fails.

xreadlines returns something that conforms to the iterator protocol.
The protocol does not require the __len__ method (which len() uses).
You can probably just use readlines() instead.  If the file is really
big you need to explicitly exhaust the iterator and keep a count, eg:

    n = 0
    for line in f.xreadlines():
        n += 1

> is there a site or mailing list that collect very small trivial python
> programs for learning purposes?

Search for "Python Cookbook".

  Neil





More information about the Python-list mailing list