Python, the `with` statement

The with statement is very helpful to simplify working with exception handling.

For example when working with files, each time we open a file, we must remember to close it.

with makes this process transparent.

Instead of writing:

filename = '/Users/flavio/test.txt'

try:
    file = open(filename, 'r')
    content = file.read()
    print(content)
finally:
    file.close()

You can write:

filename = '/Users/flavio/test.txt'

with open(filename, 'r') as file:
    content = file.read()
    print(content)

In other words we have built-in implicit exception handling, as close() will be called automatically for us.

with is not just helpful to work with files. The above example is just meant to introduce its capabilities.


This content originally appeared on flaviocopes.com and was authored by flaviocopes.com

The with statement is very helpful to simplify working with exception handling.

For example when working with files, each time we open a file, we must remember to close it.

with makes this process transparent.

Instead of writing:

filename = '/Users/flavio/test.txt'

try:
    file = open(filename, 'r')
    content = file.read()
    print(content)
finally:
    file.close()

You can write:

filename = '/Users/flavio/test.txt'

with open(filename, 'r') as file:
    content = file.read()
    print(content)

In other words we have built-in implicit exception handling, as close() will be called automatically for us.

with is not just helpful to work with files. The above example is just meant to introduce its capabilities.


This content originally appeared on flaviocopes.com and was authored by flaviocopes.com


Print Share Comment Cite Upload Translate Updates
APA

flaviocopes.com | Sciencx (2021-01-29T05:00:00+00:00) Python, the `with` statement. Retrieved from https://www.scien.cx/2021/01/29/python-the-with-statement/

MLA
" » Python, the `with` statement." flaviocopes.com | Sciencx - Friday January 29, 2021, https://www.scien.cx/2021/01/29/python-the-with-statement/
HARVARD
flaviocopes.com | Sciencx Friday January 29, 2021 » Python, the `with` statement., viewed ,<https://www.scien.cx/2021/01/29/python-the-with-statement/>
VANCOUVER
flaviocopes.com | Sciencx - » Python, the `with` statement. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/01/29/python-the-with-statement/
CHICAGO
" » Python, the `with` statement." flaviocopes.com | Sciencx - Accessed . https://www.scien.cx/2021/01/29/python-the-with-statement/
IEEE
" » Python, the `with` statement." flaviocopes.com | Sciencx [Online]. Available: https://www.scien.cx/2021/01/29/python-the-with-statement/. [Accessed: ]
rf:citation
» Python, the `with` statement | flaviocopes.com | Sciencx | https://www.scien.cx/2021/01/29/python-the-with-statement/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.