Baruch
Baruch

Reputation: 21518

Opening file 'with' statment into existing variable

When opening a file in Python, the recommended syntax is:

with open(outfile, 'wb') as f:
    pass

This creates a local variable f, even if I previously declared f (in my case, it is global f). How can I get it to use the existing variable (the global one)?

Upvotes: 0

Views: 58

Answers (1)

Ned Batchelder
Ned Batchelder

Reputation: 375804

You can use a global statement. The with ... as f statement is really just an assignment to f, so the same rules apply as with f = ...

global f
with open(outfile, "wb") as f:
   ...

Also, keep in mind that the with-statement will close the file automatically, leaving your global referring to a closed file, which is not useful.

Of course, it's better not to use global variables...

Upvotes: 2

Related Questions