Module 3: Lesson 3


Python File I/O

The third lesson introduces reading and writing data to a file by using Python. First, the Python context and the different modes by which a file can be opened (for reading, writing, or appending) are introduced. Next, reading and writing simple text data is demonstrated by using vanilla Python. Afterwards, delimited text data files are introduced, such as comma separated value (or CSV) files, which are read by using vanilla Python. Following this, Python module concept is presented and the csv module is used to simplify reading and writing comma separated value data. Finally, the Python concept of pickling is demonstrated, by which complex Python data structures can be persisted.

Objectives

By the end of this lesson, you will be be able to

  • open and close a file from a Python program,
  • read and write data from within a Python program, and
  • work with the file system by using Python.

Time Estimate

Approximately 2 hours.

Activities

Video: Watch the Python File I/O video, which will demonstrate key concepts in reading and writing data from Python as well as the how to use modules to simplify program development.

Notebook: Read and complete the practice exercises in the Python File I/O notebook.


© 2017: Robert J. Brunner at the University of Illinois.

This notebook is released under the Creative Commons license CC BY-NC-SA 4.0. Any reproduction, adaptation, distribution, dissemination or making available of this notebook for commercial use is not allowed unless authorized in writing by the copyright holder.