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.