Chapter Seven · Beyond One Run

Files

Everything so far vanished the moment a program ended. Files are how programs read what already exists and keep what they produce. This chapter covers reading text, writing without destroying what was there, finding files reliably, and reading the most common data file of all: a spreadsheet exported as CSV, in this case your own bank statement.

Up to now, every value a program worked with was typed into the program or typed by a person while it ran. Real work starts with data that already exists: a list of addresses, a log, the statement your bank lets you download. And real programs leave something behind: a report, an updated list, a record of what they did. Both directions go through files.

Four topics. Reading a text file, safely, and what text encoding is. Writing, including the one-letter difference between replacing a file and adding to it, and the careful way to replace something important. Paths: why "file not found" usually means "wrong folder", and how to build paths that work on every system. And CSV, the format every spreadsheet can export, read into the lists and dictionaries you already know.

Every file operation, in three steps
Open the filefor reading or writing
→
Read or writetext in or out
→
Close itwith does this for you

Topics in This Chapter