Python Tutorial Python Advanced Python References Python Libraries

Python with Keyword

The Python with keyword is used to wrap the execution of a block of code within methods defined by the context manager. This makes the code cleaner and much more readable.

Context manager is a class which implements __enter__ and __exit__ methods. Use of with statement ensures that the __exit__ method is called at the end of the block of code. This is similar as using try...finally block. The example below explains the same theory:

#file handing example using with statement

#1. Using try..finally block 
MyFile = open('example.txt', 'w') 
    MyFile.write('Hello World!.') 
#2. Using with statement 
with open('example.txt', 'w') as MyFile: 
    MyFile.write('Hello World!.') 

The first block of code works in the similar way as the second block of code. The above example writes the text 'Hello World!.' to the file called MyFile (example.txt). File object has __enter__ and __exit__ methods defined within it. Therefore it acts as its own context manager.

At first, the __enter__ method is called, then the block of code within with statement is executed and at last the __exit__ method is called. The __exit__ method is called even if there is an error. It basically closes the file stream.


In the example below, with keyword is used write "Hello World!." in example.txt.

with open('example.txt', 'w') as MyFile: 
    MyFile.write('Hello World!.') 

with open('example.txt', 'r') as MyFile: 

The output of the above code will be:

['Hello World!.']

❮ Python Keywords