Question

I have a python script that reads in a .csv file that works fine for Python 2.7 but is breaking on Python 2.4. The error being thrown is on the line

with open(sys.argv[1], 'rb') as csvfile:

Right here it's giving me a syntax error so my question is what does 'with' do (or whatever part of this could throw a syntax error in 2.4). I can't find documentation on this function anywhere, partly because of its generic name.

Was it helpful?

Solution

You are looking at a context manager; for relevant documentation that is an easier term to search on.

  • The original proposal PEP-343 to add the feature describes context managers in detail.

  • The datamodel documentation describes what makes a context manager. Context managers have .__enter__() and .__exit__() methods.

  • The with statement itself is documented as a compound statement in the reference documentation.

  • For file objects, the File object documentation (part of the standard types documentation) describes that most file objects can be used as context managers.

For files specifically, the relevant part you were looking for is documented with the file.close() method, because that is what the context manager .__exit__() method does for files: close the files whatever else happened.

Translating that to older Python versions where there is no support for the with statement yet, that means you have to manually close your file, with a try: finally: combination:

csvfile = open(sys.argv[1], 'rb')
try:

    # do things with csvfile

finally:
    csvfile.close()

This ensures that csvfile is properly closed whatever else happens.

OTHER TIPS

In the concrete case of opening a file, it achieves the following:

cvsfile = open(sys.argv[1], 'rb')
try:
   ...
finally:
    cvsfile.close()

Python 2.5 and later allow objects used as expressions in with (context managers) to define how they enter the context and leave it. Files will be closed when leaving with, locks will be unlocked, and so on.

PEP 343 that introduced with is still quite an informative read.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top