xxxxxxxxxx
The with statement in Python is used for resource management and exception handling
xxxxxxxxxx
# file handling
# 1) without using with statement
file = open('file_path', 'w')
file.write('hello world !')
file.close()
# 2) without using with statement
file = open('file_path', 'w')
try:
file.write('hello world')
finally:
file.close()
# using with statement
with open('file_path', 'w') as file:
file.write('hello world !')
xxxxxxxxxx
# With is used for better and more readable file handling.
# Instead of having to open and close the file:
file_handler = open('path', 'w')
file_handler.write('Hello World!')
file_handler.close()
# You can use with which will close the file for you at the end of the block:
with open('path', 'w') as file_handler:
file_handler.write('Hello World!')
# Another common use is with pickle files:
with open('pickle_path.pkl', 'rb') as file_handler:
file_contents = pickle.load(file_handler)
xxxxxxxxxx
with open("hello.txt") as my_file:
print(my_file.read())
# Output :
# Hello world
# I hope you're doing well today
# This is a text file
xxxxxxxxxx
# a simple file writer object
class MessageWriter(object):
def __init__(self, file_name):
self.file_name = file_name
def __enter__(self):
self.file = open(self.file_name, 'w')
return self.file
def __exit__(self):
self.file.close()
# using with statement with MessageWriter
with MessageWriter('my_file.txt') as xfile:
xfile.write('hello world')