CIS 2020 · Python for Everyone · Section 7.1 · Study guide

Section 7.1: reading and writing files, and working with CSV files

Every program you have written so far forgets everything the moment it stops. A file fixes that. This guide starts with the smallest possible example and adds one idea at a time: reading a file, reading it line by line, reading numbers, writing and adding to files, and finally working with CSV files, the simple spreadsheet format that almost every program can open. Every example shows what is in the file and what the program prints, so you can check your own results.

Getting set up

Before you start

A text file is just a sequence of characters saved on your disk, divided into lines. Python reads and writes it in three steps: open it, work with it, close it.

Safe file workflow using with open The program opens a text file, reads from it or writes to it, then the with statement closes the file automatically when the indented block ends. 1. open filewith open(...) 2. work with itread or write 3. block endsfile closes The with statement handles closing, even if the block ends early.
Use with open(...) so Python closes the file for you when the indented block is finished.

Make a practice file first

In Thonny (or any editor), choose File, New, type these three lines, and save the file as notes.txt in the same folder as your Python program. Most of the examples below read this file.

notes.txt

Bring a pencil.
Lab 5 is due Friday.
Office hours are at noon.

Where is my file? A short name such as "notes.txt" is looked up in the folder your program runs from. If Python says it cannot find the file, the usual causes are: the file is saved in a different folder, the name is spelled differently, or the file was saved as notes.txt.txt because your computer hides file extensions.

The three file modes

The second value you give open() is the mode. It tells Python what you plan to do with the file.

Choose the mode that matches what you want to do
ModeMeaningIf the file existsIf the file does not exist
"r"readReads it from the startError: FileNotFoundError
"w"writeErases it, then writesCreates a new empty file
"a"appendKeeps it, writes at the endCreates a new empty file

Reading

Reading a text file

There are three common ways to read: all at once, one line at a time with a loop, or one line at a time by hand.

Example 1: read the whole file at once

with open("notes.txt", "r") as file:
    contents = file.read()

print(contents)
Bring a pencil.
Lab 5 is due Friday.
Office hours are at noon.

Read the first line out loud: "open notes.txt for reading, and call it file while the block runs." file.read() returns everything in the file as one big string, newlines included. After the indented block ends, the file is closed, but the string in contents is still there to use.

Example 2: loop over the lines

A file works in a for loop just like a string or a list. Each pass hands you the next line.

with open("notes.txt", "r") as file:
    for line in file:
        print(line)
Bring a pencil.

Lab 5 is due Friday.

Office hours are at noon.

Where did the blank lines come from? Each line in the file ends with an invisible newline character, \n. Then print() adds its own newline. Two newlines make a blank line.

Example 3: fix the blank lines with strip()

with open("notes.txt", "r") as file:
    for line in file:
        print(line.strip())
Bring a pencil.
Lab 5 is due Friday.
Office hours are at noon.

strip() removes spaces, tabs, and newlines from both ends of a string. Get in the habit of stripping every line you read.

See the invisible character: try print(repr(line)) inside the loop. repr() shows the string the way Python stores it, so you will see 'Bring a pencil.\n' with the \n visible.

Example 4: number the lines

Combine the line loop with a counter, the same pattern you used in Module 7.

line_number = 1

with open("notes.txt", "r") as file:
    for line in file:
        print(line_number, line.strip())
        line_number = line_number + 1
1 Bring a pencil.
2 Lab 5 is due Friday.
3 Office hours are at noon.

Example 5: count the lines

count = 0

with open("notes.txt", "r") as file:
    for line in file:
        count = count + 1

print("The file has", count, "lines.")
The file has 3 lines.

Example 6: search for a word

with open("notes.txt", "r") as file:
    for line in file:
        if "Lab" in line:
            print("Found:", line.strip())
Found: Lab 5 is due Friday.

The in operator checks whether one string appears inside another. Only the line that contains "Lab" is printed. Remember that it is case sensitive, so "lab" would not match.

Example 7: read one line at a time with readline()

Sometimes you want just the first line, or you want to handle the first line differently from the rest. readline() reads exactly one line each time you call it.

with open("notes.txt", "r") as file:
    first = file.readline()
    second = file.readline()

print("First line:", first.strip())
print("Second line:", second.strip())
First line: Bring a pencil.
Second line: Lab 5 is due Friday.

The file remembers where you stopped reading. The second call picks up right where the first one ended. When there are no lines left, readline() returns an empty string "".

Example 8: save the lines in a list

names.txt

Ana
Ben
Chloe
names = []

with open("names.txt", "r") as file:
    for line in file:
        names.append(line.strip())

print(names)
print("Number of names:", len(names))
print("First name:", names[0])
['Ana', 'Ben', 'Chloe']
Number of names: 3
First name: Ana

append() adds an item to the end of a list. Once the names are in a list, the file can be closed and your program can still use the names as often as it likes.

Reading

Reading numbers from a file

Everything you read from a text file is a string, even if it looks like a number. Convert it with int() or float() before doing math, exactly like you do with input().

scores.txt

88
92.5
75

Example 9: what goes wrong without converting

with open("scores.txt", "r") as file:
    first = file.readline()

print(first + first)
88
88

That is not 176. The + joined two strings, "88\n" and "88\n", end to end.

Example 10: total and average

total = 0
count = 0

with open("scores.txt", "r") as file:
    for line in file:
        score = float(line)
        total = total + score
        count = count + 1

print("Total:", total)
print("Average:", round(total / count, 1))
Total: 255.5
Average: 85.2

float() and int() both ignore spaces and the newline at the ends of a string, so float("92.5\n") works without stripping first.

Example 11: find the highest score

with open("scores.txt", "r") as file:
    highest = float(file.readline())
    for line in file:
        score = float(line)
        if score > highest:
            highest = score

print("Highest score:", highest)
Highest score: 92.5

This is the maximum algorithm from Module 7: use the first value as a starting guess, then compare every later value against it. readline() grabs the first score, and the loop continues from the second line.

Blank lines break conversions. If the file ends with an empty line, float("") raises ValueError. Skip empty lines by putting if line.strip() != "": before you convert.

Writing

Writing a text file

Open the file with mode "w" and call write() with a string. Run the program, then open the new file in your editor to see what it saved.

Example 12: write two lines

with open("greeting.txt", "w") as file:
    file.write("Hello, file!\n")
    file.write("This text is saved.\n")

print("Done writing.")
Done writing.

greeting.txt after the program runs

Hello, file!
This text is saved.

Notice that the program printed only "Done writing." The text you write goes into the file, not to the screen.

Example 13: forgetting the newline

with open("oops.txt", "w") as file:
    file.write("Hello")
    file.write("World")

oops.txt

HelloWorld

Unlike print(), write() does not add a newline for you. If you want separate lines, put \n at the end of each string.

Example 14: writing numbers

total = 42

with open("total.txt", "w") as file:
    file.write(total)
TypeError: write() argument must be str, not int

write() only accepts strings. Convert the number with str(), or use an f string:

total = 42

with open("total.txt", "w") as file:
    file.write(str(total) + "\n")
    file.write(f"The total is {total}\n")

total.txt

42
The total is 42

Need a refresher on f strings? See f strings vs percent formatting.

Example 15: write a list, one item per line

foods = ["tacos", "mango", "noodles"]

with open("foods.txt", "w") as file:
    for food in foods:
        file.write(food + "\n")

foods.txt

tacos
mango
noodles

Example 16: write a small table with a loop

with open("squares.txt", "w") as file:
    for number in range(1, 6):
        file.write(f"{number} squared is {number * number}\n")

squares.txt

1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25

Example 17: save what the user types

name = input("What is your name? ")
color = input("What is your favorite color? ")

with open("profile.txt", "w") as file:
    file.write(f"Name: {name}\n")
    file.write(f"Color: {color}\n")

print("Saved your profile.")
What is your name? Maya
What is your favorite color? green
Saved your profile.

profile.txt

Name: Maya
Color: green

Write mode erases first. Run Example 17 twice and the file holds only the second answer. Opening a file with "w" wipes out whatever was in it before. Use practice files while learning, and double check the file name before you run.

Writing

Adding to a file instead of replacing it

Mode "a" (append) keeps everything already in the file and adds your new text to the end.

Example 18: a simple journal

entry = input("What did you practice today? ")

with open("journal.txt", "a") as file:
    file.write(entry + "\n")

print("Entry added.")

Run it three times, typing a different answer each time.

journal.txt after three runs

for loops
reading files
writing files

With "w" instead of "a", the file would hold only writing files, the last entry.

Example 19: append, then read it all back

with open("visits.txt", "a") as file:
    file.write("visit\n")

with open("visits.txt", "r") as file:
    count = 0
    for line in file:
        count = count + 1

print("Number of runs so far:", count)
Number of runs so far: 1

Run it again and it says 2, then 3. The program remembers between runs because the information lives in the file, not in a variable.

Reading and writing

Reading one file, writing another

A very common job: read an input file, change each line a little, and save the result in an output file.

Example 20: copy a file with line numbers

with open("notes.txt", "r") as infile:
    with open("numbered.txt", "w") as outfile:
        number = 1
        for line in infile:
            outfile.write(f"{number}. {line.strip()}\n")
            number = number + 1

print("Wrote numbered.txt")

numbered.txt

1. Bring a pencil.
2. Lab 5 is due Friday.
3. Office hours are at noon.

Two files are open at once, so give them clear names. infile and outfile are the names the textbook uses, and they make it hard to mix up which one you are reading and which one you are writing.

Example 21: copy only the lines you want

tasks.txt

done: buy notebook
todo: finish lab 6
done: email professor
todo: study for quiz
with open("tasks.txt", "r") as infile:
    with open("todo.txt", "w") as outfile:
        for line in infile:
            if line.startswith("todo"):
                outfile.write(line)

todo.txt

todo: finish lab 6
todo: study for quiz

Here the line is written exactly as it was read, newline and all, so there is no need to strip it or add \n.

Errors

When the file is missing

Opening a file that does not exist with "r" stops your program with an error. You can catch that error and print a friendly message instead.

Example 22: the error you will see

with open("nothere.txt", "r") as file:
    print(file.read())
FileNotFoundError: [Errno 2] No such file or directory: 'nothere.txt'

Example 23: ask for a file name and handle a typo

filename = input("Which file should I open? ")

try:
    with open(filename, "r") as file:
        print(file.read())
except FileNotFoundError:
    print("Sorry, I could not find", filename)
Which file should I open? notse.txt
Sorry, I could not find notse.txt

This is the same try and except shape from the input validation examples. Python tries the indented block; if the file is missing, it jumps to the except block instead of crashing.

Section 7.1, continued

Working with CSV files

CSV stands for comma separated values. It is a plain text file where each line is one row of a table and commas separate the columns. Excel, Google Sheets, and nearly every database can open and save CSV files, which makes them the easiest way to move a table of data into or out of Python.

A CSV file and the table it represents On the left, the text of students.csv: a header line name comma score, then Ana 88, Ben 92, and Chloe 75. On the right, the same data shown as a table with two columns and three rows. name,score Ana,88 Ben,92 Chloe,75 namescore Ana88 Ben92 Chloe75
The first line is usually a header that names the columns. Every line after it is one row of data.

Save this as students.csv next to your program. You can type it in Thonny, or make it in Excel or Google Sheets and choose to save or download it as CSV.

students.csv

name,score
Ana,88
Ben,92
Chloe,75

Example 24: split each line by hand

Since a CSV file is just text, you already know enough to read it. split(",") breaks a string apart at every comma and gives you a list of the pieces.

with open("students.csv", "r") as file:
    file.readline()   # read the header line and ignore it
    for line in file:
        parts = line.strip().split(",")
        name = parts[0]
        score = int(parts[1])
        print(name, "scored", score)
Ana scored 88
Ben scored 92
Chloe scored 75

For the line "Ana,88", split(",") gives the list ['Ana', '88']. Item 0 is the name and item 1 is the score, still a string until int() converts it.

Why use the csv module?

Splitting by hand breaks as soon as a value contains a comma. In a CSV file, a value like that is wrapped in double quotes:

people.csv

name,city
"Lee, Sam",Turlock
Ana,Modesto

split(",") would turn the second line into three pieces: '"Lee', ' Sam"', and 'Turlock'. Python's built in csv module understands the quotes and gets it right, so use it for any real CSV file.

Example 25: read rows with csv.reader

import csv

with open("students.csv", "r", newline="") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)
['name', 'score']
['Ana', '88']
['Ben', '92']
['Chloe', '75']

A reader hands you each row as a list of strings, already split and with the newline removed. Notice that the numbers are still strings, like '88'. Also notice the header row came out too.

Example 26: skip the header with next()

import csv

with open("students.csv", "r", newline="") as file:
    reader = csv.reader(file)
    header = next(reader)
    print("Columns:", header)
    for row in reader:
        print(row[0], "has a score of", row[1])
Columns: ['name', 'score']
Ana has a score of 88
Ben has a score of 92
Chloe has a score of 75

next(reader) reads just one row, the header, so the loop starts with the first row of real data. It works like readline() did in Example 7.

Example 27: average a column

import csv

total = 0
count = 0

with open("students.csv", "r", newline="") as file:
    reader = csv.reader(file)
    next(reader)
    for row in reader:
        total = total + int(row[1])
        count = count + 1

print("Students:", count)
print("Average score:", round(total / count, 1))
Students: 3
Average score: 85.0

Example 28: find the top student

import csv

best_name = ""
best_score = -1

with open("students.csv", "r", newline="") as file:
    reader = csv.reader(file)
    next(reader)
    for row in reader:
        score = int(row[1])
        if score > best_score:
            best_score = score
            best_name = row[0]

print("Top student:", best_name, "with", best_score)
Top student: Ben with 92

This time the maximum algorithm keeps two variables: the highest score so far and the name that goes with it. They are always updated together.

Example 29: write a CSV file with csv.writer

import csv

with open("supplies.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["item", "price"])
    writer.writerow(["pencil", 0.75])
    writer.writerow(["notebook", 2.50])
    writer.writerow(["eraser", 1.25])

supplies.csv

item,price
pencil,0.75
notebook,2.5
eraser,1.25

writerow() takes a list and writes it as one line, adding the commas and the newline for you. Unlike write(), it accepts numbers, so no str() is needed. Double click supplies.csv and it opens as a spreadsheet.

Example 30: values with commas are quoted for you

import csv

with open("people.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["name", "city"])
    writer.writerow(["Lee, Sam", "Turlock"])
    writer.writerow(["Ana", "Modesto"])

people.csv

name,city
"Lee, Sam",Turlock
Ana,Modesto

Always add newline="" for CSV files. The csv module writes its own line endings. Without newline="", Windows computers add an extra one, and every row in your file is followed by a blank row when you open it in Excel.

Example 31: read a CSV, write a new CSV

Read students.csv, decide whether each student passed (80 or higher), and save the results in a new file with an extra column.

import csv

with open("students.csv", "r", newline="") as infile:
    with open("results.csv", "w", newline="") as outfile:
        reader = csv.reader(infile)
        writer = csv.writer(outfile)

        next(reader)
        writer.writerow(["name", "score", "result"])

        for row in reader:
            name = row[0]
            score = int(row[1])
            if score >= 80:
                result = "pass"
            else:
                result = "retake"
            writer.writerow([name, score, result])

print("Wrote results.csv")

results.csv

name,score,result
Ana,88,pass
Ben,92,pass
Chloe,75,retake

Example 32: use column names with csv.DictReader

Remembering that the score is row[1] gets hard when a file has ten columns. A DictReader reads the header for you and gives each row as a dictionary, so you look up values by column name. This is the dictionary idea from Module 9.

import csv

with open("students.csv", "r", newline="") as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row["name"], "scored", row["score"])
Ana scored 88
Ben scored 92
Chloe scored 75

No next() is needed: the DictReader uses the header line as the keys. The values are still strings, so convert them before doing math.

CSV tools at a glance
CodeWhat it does
import csvLoads the csv module. Put it at the top of your program.
csv.reader(file)Gives each row as a list of strings.
next(reader)Reads one row, usually to skip the header.
csv.writer(file)Makes an object that writes rows.
writer.writerow(list)Writes one list as one CSV line.
csv.DictReader(file)Gives each row as a dictionary keyed by column name.
newline=""Add to open() whenever you use the csv module.

Your turn

Practice on your own

Try each one before looking anything up. Print as you go so you can see what your program is reading.

  1. Longest line. Read notes.txt and print the longest line and how many characters it has. (Hint: len(line.strip()).)
  2. Shopping list. Ask the user for items until they type done, writing each item to shopping.txt. Then open the file again for reading and print the list with numbers in front.
  3. Grade report. Add three more students to students.csv in Excel or Thonny. Write a program that prints each student's name and a letter grade (90 and up is A, 80 and up is B, and so on), then prints how many students earned each letter.

Quick check

If you remember only these

  • Use with open(name, mode) as file:. Python closes the file when the indented block ends.
  • "r" reads, "w" erases and writes, "a" adds to the end. Reading a missing file raises FileNotFoundError.
  • read() gets the whole file as one string, readline() gets one line, and for line in file visits every line.
  • Lines you read end with \n. Use strip() to remove it.
  • Everything read from a file is a string. Convert with int() or float() before doing math.
  • write() takes only strings and does not add a newline. Add \n yourself and use str() or an f string for numbers.
  • A CSV file is a table saved as text: one row per line, commas between columns, usually a header line first.
  • csv.reader gives each row as a list of strings; next(reader) skips the header; csv.writer and writerow() write rows.
  • Open CSV files with newline="" so Excel does not show blank rows.