Python

Open a File in Python Using the ‘with’ Statement

When it requires storing some data permanently for the programming purpose, then a file is used to do this task. Generally, the open() function is used in Python to open a file for reading and writing. The open() method returns an object to work with the file. When any file is opened by the open() function, then it requires to close the file. Using the ‘with’ statement is the alternative way of opening a file in Python. It is better than the open() function and it helps to manage the resource more efficiently because it ensures that the opened resource is closed by closing the file automatically after completing the task. The file opening error can be handled also without try-except block using the ‘with’ statement.

Syntax:

The syntax of the ‘with’ statement to open a file for reading and writing has shown below.

with open(file, mode) as file_handler

  • The first argument is mandatory and contains the filename.
  • The second argument is optional which is used to define the mode for opening the file to read or write or append.

Example-1: Read a Text File Using the ‘with’ Statement

Create a Python file with the following script that will open a text file by using the ‘with’ statement. Here, the temp.txt file will be opened for reading and the readlines() function will be used to read the content of the file and store it into a list variable. Next, the for loop will iterate the list values and print the file content. The closed attribute will be True after reading the content of the file.

#Open a file for reading using 'with' statement
with open('sales.txt') as fh:

    #Read file line by line and store in a list
    data = fh.readlines()

    #Iterate the list and print each value
    for value in data:
        print(value, end='')

#Check the file is closed or not
if fh.closed :
    print("\nThe file is closed.")

Output:

The following output will appear after executing the above script if the sales.txt file exists in the current location. The output shows that the file is closed automatically after completing the reading of the file.

Example-2: Read a Binary File by Using the ‘with’ Statement

Create a Python file with the following script that will open a binary file for reading and calculate the size of the file in bytes. The filename will be taken from the user.

#Import os module
import os

#Take the filename from the user
filename = input("Enter an image name: ")

#Check the filename exist or not
if os.path.exists(filename):

    #Open the filename for reading
    with open(filename, 'rb') as img:

        #Initialize the counter
        counter = 0

        #Read the the file content
        while img.read(True):

            #Increment the counter
            counter += 1
        print("The size of the image file is: %d bytes." %counter)
else:
    print("the file does not exist.")

Output:

The following similar output will appear after executing the above script if the bird.jpeg file exists in the current location. The output shows that the size of the file is 9946 bytes.

Example-3: Use of the Nested ‘with’ Statements

Create a Python file with the following script that will open a file for reading and open another file for writing by using the nested ‘with’ statements. The first ‘with’ statement is used to open the weekday.txt file for reading that is created before. The second ‘with’ statement is used to open the holiday.txt file for writing the specific content from the weekday.txt file.

#Open a file for reading
with open('weekday.txt', 'r') as fh_in:

    #Open a file for writing
    with open('holiday.txt', 'w') as fh_out:

        # Read file line by line and store in a list
        data = fh_in.readlines()
        for val in data:

            #Check the condition before writing
            if val.strip() == 'Saturday' or val.strip() == 'Sunday':
                fh_out.write(val)
print("Holidays are:\n")

#Opening the newly created file for reading
with open('holiday.txt', 'r') as fh:

    # Read file line by line and store in a list
    data = fh.readlines()
    for val in data:
        print(val)

Output:

The following output will appear after executing the above script.

Example-4: Open Multiple Files in a Single ‘with’ Statement

Create a Python file with the following script that will open two files for writing by using a single ‘with’ statement. The script will open the weekday.txt file for reading and some specific content of this file will be written in the out1.txt file and out2.txt file. Next, both newly written files will be opened for reading and the content of these files will be printed.

#Open two files for writing
with open('out1.txt', 'w') as fh1, open('out2.txt', 'w') as fh2:

    # Open a file for reading
    with open('weekday.txt', 'r') as fh_in:

        # Read file line by line and store in a list
        data = fh_in.readlines()
        for val in data:

            #Check the condition before writing
            if val.strip() == 'Saturday' or val.strip() == 'Sunday':
                fh2.write(val)
            else:
                fh1.write(val)

#Open two newly written files for reading
with open('out1.txt', 'r') as fh1, open('out2.txt', 'r') as fh2:
    print(fh1.readlines())
    print(fh2.readlines())

Output:

The following output will appear after executing the above script.

Example-5: Compare ‘with’ Statement with open() Function and open() function

Create a Python file with the following script that will open the same file named weekday.txt by using the ‘with’ statement and open() function. It has been shown in the previous example that the file is closed automatically after reading or writing the content, if it is opened by using the ‘with’ statement. But the file requires to close by using the close() function, if the file is opened by using the open() function that was shown by using the try-finally block in this script.

# Declare a function to check the file is closed or not
def check(f):
    if f.closed:
        print("The file has been closed.")
    else:
        print("The file has not closed yet.")

# Open a file for reading by using the 'with' statement
with open('weekday.txt') as fh:
    data = fh.read()

# Call the check() function
check(fh)

# Open a file for reading by using open() function
fh = open('weekday.txt')
try:
    data = fh.read()

    # Call the check() function
    check(fh)
finally:
    fh.close()

    # Call the check() function
    check(fh)

Output:


The following output will appear after executing the above script.

Conclusion

Different uses of the ‘with’ statement to open any file for reading or writing have been shown in this tutorial by using simple examples that will help the Python users to know the purposes of using the ‘with’ statement in Python.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.