Python & data · Lesson 11
Read and write files
Work with text files using with, explicit encoding, and careful error handling.
- 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.
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.
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.
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.
try:
with open("notes.txt", encoding="utf-8") as file:
print(file.read())
except FileNotFoundError:
print("Create notes.txt before running this example.")What can opening an existing file in write mode ("w") do?
Your turn
Write a program that reads notes.txt and prints its contents, or reports that the file is missing.
try: with open("notes.txt", encoding="utf-8") as file: print(file.read()) except FileNotFoundError: print("notes.txt was not found.")
BUILT TOGETHER
Help make this explanation better.
Have a clearer explanation, a useful example, or a correction? Share it with the community.
Be the first to add your name when you improve this lesson.
How to get credited