Long Live Python!

Alex Martelli aleaxit at yahoo.com
Thu Jul 12 05:09:10 EDT 2001

"Quinn Dunkan" <quinn at yak.ugcs.caltech.edu> wrote in message
news:slrn9kpkco.32b.quinn at yak.ugcs.caltech.edu...
> >Wasn't one solution only 2 lines? If I remember right it was Alex
> >Martelli's.
> open(output, 'w').writelines(open(input).readlines()[1:])
> ... can I go back to using python a scripting language now?
> Here's a superior solution:
> import sys
> sys.stdout.writelines(sys.stdin.readlines()[1:])
> A mere semicolon could turn this two line program monstrosity back into a
> beautifully script-like one line.

The original problem was expressed as "removing the first line
from a file", but what the original poster really wanted was
to do the operation "in-place" on ALL files in a directory.

Operations from standard-input to standard-output do not meet
the "in-place" constraint (with the redirection of most shells
I know, at least -- the '>foo' empties the file so the '<foo'
cannot read it).  What happens when the same file is opened
twice for both input and output at the same time is murky.  And
neither of these handles the issue of working on all files in
a directory.

My proposed solution relied on the fileinput module's "in-place"
behavior (WITH a backup, but that's optional I guess:-).  That
module nicely wraps whatever concerns may need to be wrapped, AND
works on as many files as you desire.

def allbutfirst(files):
    for line in fileinput.input(files,inplace=1,backup='.bak'):
        if fileinput.filelineno()>1: print line,

to be called, presumably, as:


To perform the operation on an arbitrary number of directories
named on the Python script's command line one might write, for
example (warning - untested):

import sys, os, fileinput
for dir in sys.argv[1:]:
    for line in fileinput.input(os.listdir(dir),inplace=1,backup='.bak'):
        if fileinput.filelineno()>1: print line,

Yes, this IS four lines all told, but I'm not convinced an (e.g.)
bash script to perform the identical job can be substantially
shorter and still decently readable.

How anybody could deduce from that thread that Python is not
suitable to typical scripting operations is the real mystery
to me here.


More information about the Python-list mailing list