[Tutor] More Pythonic?

Timo timomlists at gmail.com
Wed Sep 9 20:36:17 CEST 2015


Op 09-09-15 om 15:41 schreef Steven D'Aprano:
> 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)
>      
It's also possible to use multiple with statements on the same line. Can 
someone with more expert Python knowledge than me comment on whether 
it's different from using them separate as mentioned by Steven?

This is what I had in mind:

with open("writefile", 'a') as outfile, open("readfile", 'r') as infile:
     pass  # Rest of the code here


Timo




More information about the Tutor mailing list