Geoff Geoff - 2 months ago 5
Python Question

Nesting 'WITH' statements in Python

It turns out that "with" is a funny word to search for on the internet.

Does anyone knows what the deal is with nesting with statements in python?

I've been tracking down a very slippery bug in a script I've been writing and I suspect that it's because I'm doing this:

with open(file1) as fsock1:
with open(file2, 'a') as fsock2:
fstring1 = fsock1.read()
fstring2 = fsock2.read()


Python throws up when I try to
read()
from fsock2. Upon inspection in the debugger, this is because it thinks the file is empty. This wouldn't be worrisome except for the fact that running the exact same code in the debugging interperter not in a
with
statement shows me that the file is, in fact, quite full of text...

I'm going to proceed on the assumption that for now nesting
with
statements is a no-no, but if anyone who knows more has a different opinion, I'd love to hear it.

Answer

I found the solution in python's doc. You may want to have a look at this

If you are running python 3.1+ you can use it like this:

with open(file1) as fsock1, open(file2, 'a') as fsock2:
    fstring1 = fsock1.read()
    fstring2 = fsock2.read()

This way you avoid unnecessary indentation.