Python with open() Syntax

Syntax: 

with open(file_path, mode, encoding) as file:

        …

file_path: It is the path to the file to open

mode: mode of operation on the file. ex.: read, write etc. (represented by r, w, r+, w+, rb, wb etc.)

encoding: read the file in correct encoding format.

Example 1: Simple Example Using The with Statement

We already have a file name w3wiki.txt in our system, and it has the following data:

w3wiki,txt

Now we will open the file and read the contents of the file using with open() statement:

Python3




with open("w3wiki.txt","r") as gfg_file:
   file_content = gfg_file.read()
   print(file_content)


Output:

w3wiki is best for DSA

Note: Here we have used mode as “r” to read the data, because the target file has text data. In case we are reading some binary file, we need to use “rb” as the mode.

Example 2: We can also use the with statement to append or write data to the file.

We will append the string “Hello geeks!” to our w3wiki.txt file.

Python3




# appending string to file
with open("w3wiki.txt","a") as gfg_file:
   gfg_file.write("\nHello Geeks!")
     
# reading the file contents
# to verify if successfully appended the data
with open("w3wiki.txt","r") as gfg_file:
    content = gfg_file.read()
    print(content)


Output:

w3wiki is best for DSA
Hello Geeks!

Note: Here we have used “a” as the mode of opening the file, this is because we want to append to the file data. Instead, if we wanted to overwrite the file data, we would use the “w” mode.

Example 3: Using nested with open statement to open multiple files

links.txt

We have defined a links.txt file containing some random links. We will open the w3wiki.txt file mentioned above and append the content of the links file into the w3wiki.txt file.

Python3




# appending string to file
with open("w3wiki.txt", "a") as gfg_file:
    gfg_file.write("\nHello Geeks!")
 
    with open("links.txt", 'r') as links_file:
        lines = links_file.readlines()
 
    gfg_file.writelines(lines)


w3wiki.txt file contents after modification:

w3wiki,txt

Here, we can see that the contents of the links.txt file has been added to the w3wiki.txt file after running the script.

How to open a file using the with statement

The with keyword in Python is used as a context manager. As in any programming language, the usage of resources like file operations or database connections is very common. But these resources are limited in supply. Therefore, the main problem lies in making sure to release these resources after usage. If they are not released, then it will lead to resource leakage and may cause the system to either slow down or crash.

As we know, the open() function is generally used for file handling in Python. But it is a standard practice to use context managers like with keywords to handle files as it will automatically release files once its usage is complete.

Similar Reads

Python with open() Syntax:

Syntax:  with open(file_path, mode, encoding) as file:         … file_path: It is the path to the file to open mode: mode of operation on the file. ex.: read, write etc. (represented by r, w, r+, w+, rb, wb etc.) encoding: read the file in correct encoding format....

Difference of using open() vs with open()

...