[Tutor] More Pythonic?

richard kappler richkappler at gmail.com
Wed Sep 9 15:05:23 CEST 2015


Would either or both of these work, if both, which is the better or more
Pythonic way to do it, and why?

#######################

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()

######################

import whatIsNeeded

with open(readfile, 'r') as f:
    for line in f:
        try:
            if keyword in line:
                do stuff
        except:
            do nothing
        with open(writefile, 'a') as f1:
            f1.write(line)

######################

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?

regards, Richard




-- 

All internal models of the world are approximate. ~ Sebastian Thrun


More information about the Tutor mailing list