Course contentsLesson 11 of 13← Course overview
  1. 01Meet Python12 min
  2. 02Set up and run Python12 min
  3. 03Variables and data types15 min
  4. 04Strings and input15 min
  5. 05Decisions with conditionals15 min
  6. 06Repeat work with loops15 min
  7. 07Functions and return values18 min
  8. 08Work with lists16 min
  9. 09Dictionaries and tuples16 min
  10. 10Understand errors and exceptions14 min
  11. 11Read and write files16 min
  12. 12Modules and the standard library14 min
  13. 13Build a small data summary20 min

Python & data · Lesson 11

Read and write files

Edit lesson

Work with text files using with, explicit encoding, and careful error handling.

16 minProgress saves on this device
In this lesson
  • Read a text file safely
  • Understand write and append modes
  • Handle a missing file

Helpful background: Understand strings, loops, and exceptions.

Read a file

open() opens a file and returns a file object. A with block closes it when the block ends, even if an exception occurs. Specify UTF-8 when that is the file's encoding.

The example expects a file named notes.txt in the program's current working directory. A missing file raises FileNotFoundError.

Read a text filepython
with open("notes.txt", "r", encoding="utf-8") as file:
    contents = file.read()
print(contents)

Read one line at a time

For a large text file, iterate over the file object instead of reading everything into one string. Each line normally includes its newline; rstrip("\n") removes the newline character from its end.

Visit each linepython
with open("notes.txt", encoding="utf-8") as file:
    for line in file:
        print(line.rstrip("\n"))

Write deliberately

The mode "w" creates a file or truncates an existing one before writing. Use it only when replacing existing contents is intended. Mode "a" appends to an existing file or creates it if needed.

Paths can be relative to the current working directory or absolute. Check which folder your program is using before writing.

Append a notepython
with open("notes.txt", "a", encoding="utf-8") as file:
    file.write("One new idea\n")

Handle a missing file

Catch FileNotFoundError when a file may be absent and you can offer a useful next step. Other errors, such as permission problems, may need different handling.

Missing filepython
try:
    with open("notes.txt", encoding="utf-8") as file:
        print(file.read())
except FileNotFoundError:
    print("Create notes.txt before running this example.")
Knowledge check

What can opening an existing file in write mode ("w") do?

Try first; feedback appears after you check.
Apply it

Your turn

Write a program that reads notes.txt and prints its contents, or reports that the file is missing.

BUILT TOGETHER

Help make this explanation better.

Have a clearer explanation, a useful example, or a correction? Share it with the community.

Contributors

Be the first to add your name when you improve this lesson.

How to get credited
Previous lessonNext lesson