DEV Community

Cover image for The 'with' statement in python
Osinachi Chukwujama
Osinachi Chukwujama

Posted on • Edited on

The 'with' statement in python

The 'with' statement in python is used for resource management and exception handling. You'd most likely find it when operating with file streams. The statement ensures that the file stream process, for example, doesn't block other processes if an exception is raised, but terminates properly.

The code block below shows the 'try-finally' approach to file stream resource management.

file = open('file-path', 'w') 
try: 
    file.write('Lorem ipsum') 
finally: 
    file.close() 
Enter fullscreen mode Exit fullscreen mode

Normally, you'd want to use this method for writing to a file. But then 'with statement' offers a cleaner approach:

with open('file-path', 'w') as file: 
    file.write('Lorem ipsum') 
Enter fullscreen mode Exit fullscreen mode

The 'with statement' simplifies our file write process to just two lines.

It is also used in database CRUD processes. This example was gotten from this site

def get_all_songs():
    with sqlite3.connect('db/songs.db') as connection:
        cursor = connection.cursor()
        cursor.execute("SELECT * FROM songs ORDER BY id desc")
        all_songs = cursor.fetchall()
        return all_songs
Enter fullscreen mode Exit fullscreen mode

Here, the 'with statement' is used to query an sqlite database and return its content.

I hope you found this useful. Please, share other uses of the 'with statement' you have encountered in the wild.

Top comments (0)