<class '_io.TextIOWrapper'>
04. File management
Computational methods
Learning objectives
- Understand the role of files in storing and exchanging program data
- Open, read, and close text files using the
open()function - Write and append content to files using
write(),writelines(), andprint() - Handle files safely using the
withstatement - Distinguish between text and binary file modes
Introduction
Working with files is a foundational programming skill: files allow programs to read large amounts of input data without manual entry, persist results between executions, generate reports, and record logs of activity.
This lecture covers the core file input and output (I/O) capabilities of Python: reading text files line by line or all at once, writing and appending content, safe resource management, and working with binary data.
Example file
Throughout this lecture we will be using an example file to perform basic IO operations in Python. Download the file available in the following url: https://example-files.online-convert.com/document/txt/example.txt
This file must be saved in the same folder as your Python code.
Reading files
Python offers the built-in open() function to open a file by returning a TextIOWrapper object that can be further manipulated. The function requires at least two arguments: the file path and the opening mode. The most common modes are:
| Mode | Description |
|---|---|
'r' |
Read (default) |
'w' |
Write (creates or overwrites) |
'a' |
Append (creates or adds to end) |
'b' |
Binary |
'+' |
Read and write |
'x' |
Create only |
After manipulating a file you must close it with the close() method to release system resources.
Reading the entire file
The read() method returns the entire file content as a single string:
TXT test file
Purpose: Provide example of this file type
Document file type: TXT
Version: 1.0
Remark
<class 'str'>
Reading a single line
The readline() method reads a single line from the file each time it is called:
TXT test file
Purpose: Provide example of this file type
Document file type: TXT
Version: 1.0
Note that each line ends with a newline character, which is recognized as such during print. This behaviour can be supressed by passing the end='' argument to print().
Reading all lines
The readlines() method returns all lines of the file as a list of strings:
TXT test file
Purpose: Provide example of this file type
Document file type: TXT
Version: 1.0
<class 'list'>
Reading with a while statement
We can combine the readline() method with a while loop to read only until a specific condition is satisfied — for example, stopping at the first blank line recognized with the '\n' character:
Reading through the with statement
Python provides the with statement as a safer and more concise way to work with files. The file is closed automatically when the block exits, even if an exception is raised, thus eliminating the risk of leaving a file open by mistake:
It is considered best practice to use with open() instead of open() + close() whenever possible, since it produces cleaner and safer code to handle files.
Writing files
Three modes are available for writing with the open() function:
| Mode | Description |
|---|---|
'x' |
Create only — raises an error if the file already exists |
'w' |
Write — creates a new file or overwrites an existing one |
'a' |
Append — creates a new file or adds to an existing one |
Write mode
The write() method writes a string to a file opened in 'w' mode. If the file already exists, its contents are overwritten. Use '\n' to insert a newline character:
Append mode
In append mode 'a', new content is added at the end of the file without overwriting existing content:
Writing with the print function
The print() function can write to a file via its file argument. Unlike write(), it appends a newline automatically:
This is the first line of the file
This is the second line of the file
Writing multiple lines
The writelines() method writes a list of strings to the file in one call. Newline characters must be included in the strings explicitly:
Binary mode
Files can also be read and written in binary mode using 'rb' and 'wb'. Binary data is represented as bytes or bytearray objects:
Exercises
The following exercises use the file example.txt. Download it and save it in the same folder as this notebook before running the cells.
Exercise 1 — Read the last line
Write a program that reads example.txt and prints only the last line of the file.
Strategy:
- Open the file in
'r'mode and usereadlines()to load all lines into a list. - Extract the last element using negative indexing:
lines[-1]. - Print the last line using
end=''to suppress the extra blank line.
Exercise 2 — Copy the last two lines to a new file
Write a program that reads example.txt, writes its last two lines into a new file called demo.txt, and prints the contents of demo.txt.
Strategy:
- Read all lines from
example.txtusingreadlines(). - Extract the last two lines using
lines[-2:]. - Write them to
demo.txtusingwritelines(). - Open and print
demo.txtto verify the result.
Exercise 3 — Count lines in a file
Write a program that reads example.txt and prints the total number of lines it contains.
Strategy:
- Open the file and read all lines using
readlines(). - Use
len()on the resulting list to count the lines.
Exercise 4 — Search for a word
Write a program that reads example.txt line by line and prints every line that contains the word 'file' (case-insensitive).
Strategy:
- Open the file and iterate over its lines using
readlines(). - For each line, use
'file' in line.lower()to check for the word. - Print matching lines using
end=''.
Exercise 5 — Append a timestamp
Write a program that appends the current date and time as the last line of file.txt. If file.txt does not exist, it should be created.
Strategy:
- Import the
datetimeclass from thedatetimemodule. - Open
file.txtin append mode'a'. - Write a line such as
'Last updated: 2026-05-22 10:30:00\n'using an f-string anddatetime.now().
Exercise 6 — Write a multiplication table
Write a program that generates the multiplication table for a given number n (e.g. n = 7) and writes the results to a file called tabla.txt, one result per line in the format 7 x 1 = 7.
Strategy:
- Open
tabla.txtin write mode'w'. - Use a
forloop overrange(1, 13)to generate each row. - Write each row as a formatted string using
write().
Exercise 7 — Binary round-trip
Write a program that encodes the string 'Python' as a bytearray using ASCII codes, writes it to a binary file called message.bin, reads it back, decodes it, and prints the result.
Strategy:
- Use
bytearray(b'Python')or list the ASCII codes manually. - Write the
bytearraytomessage.binusing mode'wb'. - Read the file back using mode
'rb'and call.decode()on the result.
Challenge — Personal records registry
Write a program that allows the user to register personal information (name, age, and email) into a text file called records.txt, using the following format:
Name: [name]
Age: [age]
Email: [email]
Requirements:
- The program must support adding multiple records.
- After each record, it must ask the user whether to add another.
- The program ends when the user replies
'No'.
Strategy:
- Collect user input with the built-in
input()function. - Open
records.txtin append mode'a'so existing records are preserved. - Write each record field using
write()with an f-string. - Control the loop with a
whilestatement checked against the user’s response.