̽̽

Introduction

Author

Clayton Cafiero

Published

2025-01-05

So far all of the input to our programs and all of the output from our programs has taken place in the console. That is, we’ve used input() to prompt for user input, and we’ve used print() to send output to the console.

Of course, there are a great many ways to send information to a program and to receive output from a program: mice and trackpads, audio data, graphical user interfaces (“GUIs”, pronounced “gooeys”), temperature sensors, accelerometers, databases, actuators, networks, web APIs (application program interfaces), and more.

Here we will learn how to read data from a file and write data to a file. We call this “file i/o” which is short for “file input and output.” This is particularly useful when we have large amounts of data to process.

In order to read from or write to a file, we need to be able to open and close a file. We will do this using a context manager.

We will also see new exceptions which may occur when attempting to read from or write to a file, specifically FileNotFoundError.

Learning objectives

  • You will learn how to read from a file.
  • You will learn some of the ways to write to a file.
  • You will learn some valuable keyword arguments.
  • You will learn about the csv file format and Python module, as well as how to read from and write to a .csv file.

Terms and Python keywords introduced

  • as
  • context manager
  • CSV (file format)
  • keyword argument
  • with

Copyright © 2023–2025 Clayton Cafiero

No generative AI was used in producing this material. This was written the old-fashioned way.

Reuse