Why with open(…) as … in python

with open(path) as f:

Python’s “with open(…) as …” Pattern[1]

with open('data.txt', 'r') as f:
data = f.read()
with open('data.txt', 'w') as f:
data = 'some data to be written to the file'





Data Scientist/MLE/SWE @takemobi

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Closing a Chapter

The un-examined team eventually plateaus; 3 steps to a great retrospective

Enriching Large Data Sets with Akka Streams

Building Responsive Layouts with Jetpack Compose

GSOC’20 Week 10 Update

Hadoop Screening Q&A

4 Solutions to Microsoft Word Won’t Open on Mac

AWS EKS Kubernetes Versions Upgrade and Update Management

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jimmy Shen

Jimmy Shen

Data Scientist/MLE/SWE @takemobi

More from Medium

Two types of abstractions in Python: Instance of ; Inherited from

Python functional programming processing functions: map () , Filter () , reduce ()

Import and Export Data in Python

Python Morsels — CyclicList