Python “with” Statement By Examples – POFTUT

Python “with” Statement By Examples


Python provides with statements in order to exception and resource handling. There is already exception and resource handling features in Python but by using with it is accomplished more elegant and clear way.

with Statement Usage

with statement can be used in different cases. We will list the most popular with statement usage in Python.

  • `File Handling`
  • `Exception Handling`
  • `Management of unmanaged resources`

with Statement Syntax

with statement has very different syntax according to the other Python statements and keywords.

with EXPRESSION as VARIABLE:
   CODE-BLOCK
  • `with` is the keyword
  • `EXPRESSION` is the expression which will run inside the with for exception handling and resource management
  • `VARIABLE` is optional but used to create a variable from the EXPRESSION which will be used inside the CODE-BLOCK
  • `CODE-BLOCK` is the code block where with statement is created. VARIABLE only available inside this code block. CODE-BLOCK also creates a block where resource and exceptions are automatically handled

with Statement File Operations

One of the most popular use cases for the with statement is file operations like open, read, write, etc. We can open a file in a secure manner by using with helping exception handling and resource management. Even we do not close the opened file with statement will handle it and close the file.

with open('test.c','w') as file:
   file.write('hello world!')
with Statement File Operations
with Statement File Operations

Try-Finally vs with Statement

As stated previously with statement can function like try-finally statements in order to catch exceptions. Here we will compare the try-finally and with statements each other.

with open('test.c','w') as file:
   file.write('hello world!')

OR

file = open('file_path', 'w') 
try: 
   file.write('hello world') 
finally: 
   file.close()

LEARN MORE  What Is EOF (End Of File)? Examples with PHP, C++, C, Python, Java

Leave a Comment