<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
- Write and append content to files
- 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.
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.
Lets considering the file example.txt to perform a basic open and close operation:
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 until a specific condition is satisfied — for example, stopping at the first blank line recognized with the '\n' character:
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 with the 'w' mode. If the file already exists, its contents are overwritten. You can 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
Interenstingly, the print() function can also be used to 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 in each line:
Binary mode
Files can also be read and written in binary mode using 'rb' and 'wb', respectively. Binary data is represented as bytes or bytearray objects:
Exercises
- Write a program that reads
example.txtand prints the total number of lines it contains. - Write a function that reads the file
example.txtand prints a single line specified by the user. - Write a program that reads
example.txtline by line and prints every line that contains the word'John'(case-sensitive). - Write a function that reads
example.txt, writes a number of lines specified by the user with a list into a new filedemo.txt, and print the contents ofdemo.txt. - Write a program that encodes the string
'Python'as abytearrayusing ASCII codes, writes it to a binary file calledmessage.bin, reads it back, decodes it, and prints 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(). - Control the loop with a
whilestatement checked against the user’s response.