0

I have both csv readers and writers. I understand you have to open and close the underlying object. One way to do it it would be to first create the file object, f, use csv reader and then use f.close().

However, I can't seem to do the following:

with open(outputpath) as f_outputfile:

    outputfile = csv.writer(f_outputfile)

OTHER CODE HERE

What I want to do is open a bunch of readers at once and a bunch of writers at once and have them all close automatically. However, does that mean I have a nested "With" block?

4
  • 2
    Does OTHER CODE HERE use f_outputfile? Commented May 17, 2012 at 19:19
  • More appropriately, is OTHER CODE HERE the part that writes to the csv file? Commented May 17, 2012 at 19:21
  • Yes, it does. Say I want 3 readers and 2 writers and they all need each other. Other CODE HERE writes the CSV file. Commented May 17, 2012 at 19:22
  • 1
    Then you should make OTHER CODE HERE part of the with block. Commented May 17, 2012 at 19:25

2 Answers 2

5

Writing:

with open(outputpath) as f_outputfile:
    outputfile = csv.writer(f_outputfile)

OTHER CODE HERE

Is essentially the same as:

f_outputfile = open(outputpath)
try:
    outputfile = csv.writer(f_outputfile)
finally:
    f_outputfile.close() 

OTHER CODE HERE

If OTHER CODE HERE relies on the file being open, it's not going to work.

Sign up to request clarification or add additional context in comments.

1 Comment

It's only essentially the same if csv.writer can't throw exceptions (which is never true in python).
3

You can stack multiple items in the with statement as in (looks like this is a 2.7.x and higher feature):

with open(foo) as f_foo, open(bar) as f_bar:
    # do something

7.5. The with statement

New in version 2.5.

The with statement is used to wrap the execution of a block with methods defined by a context manager (see section With Statement Context Managers). This allows common try...except...finally usage patterns to be encapsulated for convenient reuse.

with_stmt ::=  "with" with_item ("," with_item)* ":" suite
with_item ::=  expression ["as" target]

3 Comments

This throws an error, not sure why then: with open(outputpath,"w") as f_outputfile, open(inputpath, "r") as f_inputpath:
Just verified it works in 2.7.3, what version are you using? Just took a peek at the 2.6 docs and there it only allows single with_item's this is probably a 3.x feature back-ported to 2.7.x
I'm using 2.6.6, that must be why. It's ok, I can do nested "withs". Just to make sure, I don't need to worry about close commands now yes? They will now close automatically?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.