newbie Q: delete list few lines in file

Peter Hansen peter at engcorp.com
Sat Jun 29 20:30:27 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.
> 
> if you can show me a script that'll be great otherwise my question can
> be broken down as:
> 
> * how to write to file inplace? (or, do i write to a new file, then
> delete original, and rename the new file?)

You cannot write files in place.  I don't understand why you would
want to, however, since your purpose was to delete them, not change
them.  (Or did I misunderstand?)

If you did have to modify, however, the tempfile module could be helpful 
for you here, as well as os.remove and os.rename.

> * 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.

You shouldn't need to read the individual lines this way if you 
are looking for *exactly* that pattern.  Just do something like this:

f = open(filename)
data = f.read()
f.close()
if data.find('some mailing list\nsome at list.com\nhttp://some.com/ttt\n') >= 0:
    print 'Removing evil file %s' % filename
    os.remove(filename)

> I'm much more interested in learning python idiom and correctness
> here. I'm not interested in just "get it to work". For the latter, i
> can do well with perl. (also, is there a site or mailing list that
> collect very small trivial python programs for learning purposes?)

Well, Python idioms are all about just "getting it to work" :-),
but doing it cleanly and readably.  Other than that, it's just like
Perl programming. :-)

-Peter



More information about the Python-list mailing list