Trusted answers to developer questions

The 'with' statement in Python

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

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 working with file streams. For example, the statement ensures that the file stream process 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() 

Normally, you’d want to use this method for writing to a file, but the with statement offers a cleaner approach:

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

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

It is also used in database CRUD processes. This example was taken 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

Here, with is used to query an SQLite database and return its content.

I hope you found this useful.

RELATED TAGS

python3
stream

CONTRIBUTOR

Osinachi Chukwujama
Did you find this helpful?