Using context managers (with statement) in python

Using context managers (with statement) in python

Context managers features in Python programs specially Python file close with with statement provides a convenient way to work with open and close files in Python file handling operations. During file handling operation with statement ensures that the file is opened and closed properly in the current file operation read and write file operation even if any error is displayed during file handling operation.

So let’s see how to use context managers features with with statement in Python file handling.

Reading from file in file handling.

Read sample.txt file using context manager.

file_location = ‘sample.txt’

# here with statement open and close you file automatically

with open(file_location, ‘r’) as file: # open file with statement for read operation

for line in file:

print(line.strip()) # this function process on file text lines

In the above program example.

open(file_location, ‘r’) opens the sample.txt file in read only mode (‘r’).

with open(…) as file – Here with statement manually assigns the file object to be opened, and here with statement confirms the open file to be closed automatically after proper execution of the indented block of code (with block).

Writing to a Python file.

You can write information to a file using the file handling context manager features as above.

file_location = ‘sample.txt’

# here with statement use to automatically close the open file after file operation done

with open(file_location, ‘w’) as file:

file.write(“let explore python with statement \n”)

file.write(“with statement automatically close open file when task done”)

In the above program.

open(file_location, ‘w’) opens the sample.txt file in write mode (‘w’). Which will shrink the open file if it already exists, if the file does not already exist then it will create a new file in write mode.

We already know that in Python file handling, write() file method is used to write data and information in a new file.

Appending text/info to a Python file.

Adding text and information to a file using context manager in an existing Python file program.

file_location = ‘sample.txt’

# with statement use top oepn and close file

with open(file_location, ‘a’) as file: # here sample.txt file open for appending operation

file.write(“let add some text in exisitng sample.txt file \n”)

In the above file append operation.

open(file_location, ‘a’) in sample.txt file append mode (‘a’) Opens the file in append mode with text and information. Remember append mode will add the appended text and information at the end of the file you created earlier. While the previously created file text and information will remain as it is.

Advantage of context manager in Python program.

There are many advantages of with statement in Python file handling program operation.

File automatic resource management – In Python program it ensures that the operated file is properly opened and closed during file operation, whether your file program code block is executed successfully or program error/exception is generated.

File cleaner code – Reduces the process of writing boilerplate code in many Python programs to open and close files explicitly in file handling, and improves existing file handling program readability and maintainability.

File exception handling – It simplifies error handling by automatically managing file closing and file cleanup even when the current file handling program is inside an exception block.

Error Management with Context Manager in Python.

You can add error management to the with statement by using a try-except exception block to manage specific exceptions that may arise during Python file handling operations.

Error Management with Context Manager in Python Programs.

file_location = ‘sample.txt’

try:

with open(file_location, ‘r’) as file:

for line in file:

print(line.strip()) # stip function used to process each line in file

except FileNotFoundError:

print(f”Error – display the file not found error ‘{file_location}’ file not available.”)

except PermissionError:

print(f”Error – file permission restricted ‘{file_location}’.”)

except IOError as e:

print(f”Error – file disk open error {e}”)

In the above Python file handling operation, you can manage multiple file handling program exception errors using context manager. Where multiple file exceptions can be managed using with statement and try block statement.