File processing

Steve Holden sholden at holdenweb.com
Mon Jul 9 17:57:45 EDT 2001


"Chris McMillan" <christopherjmcmillan at eaton.com> wrote in message
news:9id5p9$8r62 at interserv.etn.com...
> Hello all!
>
> I'm trying to write a script that will open a file, delete the first line,
> and then save the file with the same name.  Can someone please point me in
> the right direction?  Thanks!
>
> Why am I doing this you may ask: I have tens of data files that I need to
> strip the first line before I can process it in Matlab.  So, I dream of a
> script that opens every file in a directory, deletes the first line, .....
>
Unfortunately "delete the first line" isn't a canonical file operation, so
you have to read the whole input file in and copy everything but the first
line. Something like this ought to do it, though I haven't tested it:

def trimline1(oldfile, newfile):
    inf = open(oldfile, "r")
    junk = inf.readline()
    open(outf, "w").write(inf.read())
    inf.close()

That last line is just an abbreviated way to say "open the output file, read
the remainder of the input file, and write what was just read to the
output". Because no reference is saved to the output file, it should be
closed automatically. Absolute caution might recommend (if you want the
close to be explicit):

def trimline1(oldfile, newfile):
    inf = open(oldfile, "r")
    junk = inf.readline()
    outf = open(outf, "w")
    outf.write(inf.read())
    inf.close()
    outf.close()

but it isn't as snappy. Because exiting the function also destroys the
reference to the input file you could probably also omitthe close() on that,
but why bother if you're just going to copy'n'paste?

Of course, that still leaves you with the problem of calling this function
tens of times. Take a look at the glob module for that.

regards
 Steve
--
http://www.holdenweb.com/








More information about the Python-list mailing list