Unit 8Working with Files

A file is a non-volatile container for long-term data storage. A typical file operation involves opening a file, reading data from the file or writing data into the file, and closing the file. You can open a file for reading (default mode, denoted as "r"), [over]writing ("w"), or appending ("a"). Opening a file for writing destroys the original content of the file without notice, and opening a non-existing file for reading causes an exception:

 f = open(name, mode=​"r"​)
 read the file
 f.close()

Python provides an efficient replacement to this paradigm: the with statement allows us to open a file explicitly, but it lets Python close the file automatically after exiting, thus saving us from tracking the unwanted open ...

Get Data Science Essentials in Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.