Python with: The Complete Guide

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

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. 


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 better syntax and exception handling.

The “with” statement simplifies exception handling by encapsulating standard 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.

Let’s write the same code but use 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.

That’s it.

Leave a Comment

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