
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()
Normally, you'd want to use this method for writing to a file. But then 'with statement' offers a cleaner approach:
withopen('file-path','w')asfile:file.write('Lorem ipsum')
The 'with statement' simplifies our file write process to just two lines.
It is also used in database CRUD processes. This example was gotten fromthis site
defget_all_songs():withsqlite3.connect('db/songs.db')asconnection:cursor=connection.cursor()cursor.execute("SELECT * FROM songs ORDER BY id desc")all_songs=cursor.fetchall()returnall_songs
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)
For further actions, you may consider blocking this person and/orreporting abuse