[Tutor] More Pythonic?
Steven D'Aprano
steve at pearwood.info
Wed Sep 9 15:41:08 CEST 2015
On Wed, Sep 09, 2015 at 09:05:23AM -0400, richard kappler wrote:
> Would either or both of these work, if both, which is the better or more
> Pythonic way to do it, and why?
The first works, but isn't really the best way to do it:
> #######################
>
> import whatIsNeeded
>
> writefile = open("writefile", 'a')
>
> with open(readfile, 'r') as f:
> for line in f:
> if keyword in line:
> do stuff
> f1.write(line)
> else:
> f1.write(line)
>
> writefile.close()
>
> ######################
Better would be this:
with open("writefile", 'a') as outfile:
with open("readfile", 'r') as infile:
for line in infile:
if keyword in line:
do stuff
outfile.write(line)
(I think your intention is to always write the lines into the output
file, but there are enough typos in your version that I can't be
completely sure.)
This, on the other hand, is certainly not what you want:
> import whatIsNeeded
>
> with open(readfile, 'r') as f:
> for line in f:
> try:
> if keyword in line:
> do stuff
> except:
> do nothing
Why are you ignoring *all errors*? That will make it impossible (or at
least very hard) to cancel the script with Ctrl-C, and it will cover
up programming errors. Apart from a very few expert uses, you should
never use a bare except. If you really want to "ignore all errors", use
`except Exception`, but even that is not good practice. You should list
and catch only the precise errors that you know you wish to ignore and
can safely handle. Everything else indicates a bug that needs fixing.
By the way, "do nothing" in Python is spelled "pass".
> with open(writefile, 'a') as f1:
> f1.write(line)
And this will repeatedly open the file, append one line, then close it
again. Almost certainly not what you want -- it's wasteful and
potentially expensive.
> ######################
>
> or something else altogether?
>
> I'm thinking the first way is better as it only opens the files once
> whereas it seems to me the second script would open and close the writefile
> once per iteration, and the do nothing in the except seems just wrong to
> me. Is my thinking on target here?
Spot on target.
--
Steve
More information about the Tutor
mailing list