[Tutor] More Pythonic?
Peter Otten
__peter__ at web.de
Wed Sep 9 20:59:42 CEST 2015
Timo wrote:
> 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
This requires Python 2.7 or higher. Other than that the choice is merely a
matter of taste. Both versions even produce the same bytecode:
$ cat nested_with.py
def f():
with open("writefile", 'a') as outfile, open("readfile", 'r') as infile:
pass # Rest of the code here
def g():
with open("writefile", 'a') as outfile:
with open("readfile", 'r') as infile:
pass # Rest of the code here
print(f.__code__.co_code == g.__code__.co_code)
$ python nested_with.py
True
Personally I find one item per with statement more readable and don't care
about the extra indentation level.
More information about the Tutor
mailing list