Python: Open a file using “open with” statement and benefits explained with examples

Opening a file using ‘open with’ statement and benefits in Python.

In this article we will discuss about how to open a file using ‘open with’ statement, how to open multiple files in a single ‘open with’ statement and finally its benefits. So, let’s start the topic.

The need for “open with” statement :

To understand the “open with” statement we have to go through opening a file in python. For that we can make use of the open( ) function that is in-built in python

File.txt-

New File Being Read.
DONE!!
#program :

# opened a file 
fileObj = open('file.txt')
# Reading the file content into a placeholder
data = fileObj.read()
# print file content
print(data)
#close the file
fileObj.close()
Output :
New File Being Read.
DONE!!

In case the file does not exist it will throw a FileNotFoundError .

How to open a file using “open with” statement in python :

#Program :

# opened a file using open-with
with open('file.txt', "r") as fileObj:
    # Reading the file content into a placeholder
    data = fileObj.read()
    # print file content
    print(data)
# Check if file is closed
if fileObj.closed == False:
    print('File is not closed')
else:
    print('File is already closed')
New File Being Read.
DONE!!
File is closed

The with statements created an execution block that will automatically delete any object that was created in the program, in this case even if it was not closed the reader object was deleted that closed the file automatically. This saves us some memory in case we forgot to close the file.

Benefits of calling open() using “with statement” :

  • Fewer chances of bug due to coding error

With “with” statement we don’t have to close the opened file manually. It takes care of that when the compiler goes out of the block and automatically closes file. So it reduces the chances of bugs, lines of code and releases the memory for other operations.

  • Excellent handling in case of exception

If we have used “open-with” statement to open a file, and an exception occurs inside the with block, the file will be closed and the control moves to the except block.

# Python :

# Before handling the exception file will be closed 
try:
    # using "with statement" with open() function
    with open('file.txt', "r") as fileObj:
        # reading the file content
        data = fileObj.read()
        # Division by zero error
        x = 1 / 0
        print(data)
except:
    # handling the exception caused above
    print('Error occurred')
    if fileObj.closed == False:
        print('File is not closed')
    else:
        print('File is closed')
Output :
Error occurred
File is closed
  • Open multiple files in a single “with statement” :

We can use open with statement to open multiple files at the same time. Let’s try reading from one file and writing into another-

# Program :

# Read from file.txt and write in output.txt
with open('output.txt', 'w') as fileObj2, open('file.txt', 'r') as fileObj1:
    data = fileObj1.read()
    fileObj2.write(data)
    # Both the files are automatically close when the control moves out of the with block.

This will generate a “outuput.txt” file that will have the same contents as our old “file.txt”.

Output : 
Output.txt- 
New File Being Read. 
DONE !!

The files will automatically close when the control moves outside the with block.