Reading and writing text files
Real Python programs rarely live entirely in memory. They read input from files, produce output as files, and leave artifacts behind that other tools or programs can use. If we want Python to generate pages, reports, or datasets, we need a simple way to move text between our code and the filesystem.
This lesson introduces the basic mechanics of working with plain text files. We focus on the smallest set of ideas needed to recognize how file input and output fits into real programs.
What a text file is
A text file is a sequence of characters stored on disk. Unlike binary files, its contents are meant to be read and written as human-readable text.
In practice, text files often hold things like HTML, configuration data, logs, or generated output. Python treats these files as streams of characters rather than structured objects.
Opening a file for reading
Before Python can read a file, the file must be opened. Opening a file establishes a connection between the program and the file on disk.
When we open a file for reading, we tell Python that we want to consume its contents without modifying them.
file = open("planets.html", "r")
The second argument indicates the mode. The "r" mode means read-only access.
Reading text from a file into a string
Once a file is open for reading, its contents can be pulled into memory as text. A common approach is to read the entire file into a single string.
file = open("planets.html", "r")
html = file.read()
At this point, html holds all the text from the file, ready to be inspected or processed.
Opening a file for writing
Writing to a file also starts by opening it, but in a different mode. Opening a file for writing tells Python that we intend to send text to disk.
file = open("index.html", "w")
The "w" mode opens the file for writing. If the file already exists, its contents are replaced.
Writing text data to a file
After opening a file for writing, text can be sent to it directly from a string. This is how programs generate output files.
file = open("index.html", "w")
file.write("<h1>Planets of the Solar System</h1>")
The string is written exactly as provided, making this approach well suited to generating HTML or other text-based formats.
Conclusion
We now have a clear mental model for text files in Python. A file is opened in a specific mode, text flows between the file and strings, and the program controls when reading or writing occurs.
This is enough orientation to recognize file input and output in real code and to start using files as durable inputs and outputs for Python programs.