Python Foundations · Lesson 11 of 12Working with text files
Writing, reading and with-open blocks. Learn through short examples, practical tasks and targeted questions.
← All lessons
Reading and writing text files
Text files let a program retain simple data between runs. Opening a file with with closes it automatically at the end of the block. Try writing a few lines, reading them back and checking whether extra newline characters affect the output.
Watch out: Opening a file in write mode replaces its previous contents. Use append mode when earlier lines must be preserved.
A free TutorSyntax programming lesson. About our teaching approach.
APPLY THE IDEA
Use this skill beyond the example
Test file code using a known small file before trying larger datasets. Explain why with open(...) is usually safer than leaving a file open, and handle the possibility that the requested file is missing.
Quick check: What happens when opening a missing file for reading without handling errors?
Check: Python raises FileNotFoundError.
Continue with related practice →