Geoff Geoff - 1 year ago 67
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 =
fstring2 =

Python throws up when I try to
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
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
statements is a no-no, but if anyone who knows more has a different opinion, I'd love to hear it.

Answer Source

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 =
    fstring2 =

This way you avoid unnecessary indentation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download