Skip to Content
Learn Python by Building Data Science Applications
book

Learn Python by Building Data Science Applications

by Philipp Kats, David Katz
August 2019
Beginner
482 pages
12h 56m
English
Packt Publishing
Content preview from Learn Python by Building Data Science Applications

Understanding the with statements

Last but not least, the with statement is usually used with any kind of connections or managed resources such as file handles. Consider the following example:

with open('./text_file.txt', 'r') as file:    data = file.read()print(data)

Here, we use a with clause together with the open() function. The open function returns a file-like object that has __enter__ and __exit__ methods, representing the opening and closing of the file. Both can be used directly, but the file needs to be closed properly once it is opened. The close() function along together with the with clause does exactly that – it opens an object, and makes sure it is closed (using those two methods) at the end. Essentially, it is the equivalent ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python for Data Science

Python for Data Science

Yuli Vasiliev
Introduction to Machine Learning with Python

Introduction to Machine Learning with Python

Andreas C. Müller, Sarah Guido

Publisher Resources

ISBN: 9781789535365Supplemental Content