Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

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 modeExit fullscreen mode

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')
Enter fullscreen modeExit 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 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
Enter fullscreen modeExit 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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Learning server-side development. Creating courses on educative.io
  • Location
    Owerri Nigeria
  • Education
    Federal University of Technology Owerri
  • Joined

More fromOsinachi Chukwujama

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp