Latest Code Tutorials

Python With: How to Use with() and open() Methods

In Python, you need to give access to the file by opening it. You can do it by using an open() function. Open returns the file object, which has methods and attributes for getting information about and manipulating the opened file.

Python With Statement

Python With Statement is used to open files. It is generally recommended because it ensures that open file descriptors are closed automatically after program execution leaves the context of the with statement. 

Let’s see an example of with statement in python.

with open('app.txt', 'w') as f:

In the above code, we have opened up a file in write mode and written that file. With the “with” statement, you get the better syntax and exceptions handling. The “with” statement simplifies exception handling by encapsulating common preparation and cleanup tasks.

Without Python with statement

Let’s see an example where we do not use with statement and handling file operations in Python.


file = open('app.txt')
data =

See the output below.

Python With Statement Tutorial Example

Opening a file using with is as simple as: with open(filename) as the file.

Above code using With Statement

Let’s write the same code, but using with statement and see the output.


with open('app.txt') as file:
   data =

The output is the same, but here we have used the with statement to read the file and printing in the console.

Write above code using With Statement

Here notice that we have not used a file.close() function. That function will be automatically called.

Finally, Python With Statement Example is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.