[Tutor] More Pythonic?

Peter Otten __peter__ at web.de
Wed Sep 9 15:37:37 CEST 2015


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?
> 
> #######################
> 
> 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)

Why do you invoke f1.write() twice?

> writefile.close()
> 
> ######################
> 
> import whatIsNeeded
> 
> with open(readfile, 'r') as f:
>     for line in f:
>         try:
>             if keyword in line:
>                 do stuff
>         except:

What exceptions are you expecting here? Be explicit. You probably don't want 
to swallow a KeyboardInterrupt. And if something unexpected goes wrong a 
noisy complaint gives you the chance to either fix an underlying bug or 
explicitly handle the exception in future runs of the script.

>             do nothing

That's spelt 
              pass

>         with open(writefile, 'a') as f1:
>             f1.write(line)

Opening the file once per line written seems over-the-top to me.
 
> ######################
> 
> or something else altogether?

I tend to put the processing into into a generator. That makes it easy to 
replace the source or the consumer:

def process_lines(instream):
    for line in instream:
        if keyword in line:
            do stuff
            yield line

with open(sourcefile) as instream:
    with open(destfile, "a") as outstream:
        outstream.writelines(process_lines(instream))

Now if you want to read from stdin and print to stdout:

sys.stdout.writelines(process_lines(sys.stdin))

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

It's not clear why you need the try...except: pass.
Please provide some more background information.




More information about the Tutor mailing list