04. File management

Computational methods

Author

Marco A. Alsina

Published

May 22, 2026

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(), and print()
  • Handle files safely using the with statement
  • 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
Important

After manipulating a file you must close it with the close() method to release system resources.

# open file in read mode
file  = open('example.txt', 'r')

# check file type object
print(type(file))

# closing file
file.close()
<class '_io.TextIOWrapper'>

Reading the entire file

The read() method returns the entire file content as a single string:

# open file in read mode
file = open('example.txt', 'r')

# read the entire content and close the file
content = file.read()
file.close()

# print the first 100 characters
print(content[:100])
print(type(content))
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:

# open file in read mode
file = open('example.txt', 'r')

# read and print the first 4 lines
for i in range(4):
    line = file.readline()
    print(line)
file.close()
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:

# open file in read mode
file = open('example.txt', 'r')

# read all lines and print the first four
lines = file.readlines()
for line in lines[:4]:
    print(line, end='')
file.close()

print(type(lines))
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:

# open and read file line by line
file = open('example.txt', 'r')
line = file.readline()

while line != '\n':
    print(line, end='')
    line = file.readline()

file.close()
TXT test file
Purpose: Provide example of this file type
Document file type: TXT
Version: 1.0
Remark:

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:

with open('filename', 'mode') as file:
    # work with file here
    ...
# file is automatically closed here

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.

# open and read a file using a with statement
with open('example.txt', 'r') as file:
    content = file.read()

# printing the first 100 characters
print(content[:100])
TXT test file
Purpose: Provide example of this file type
Document file type: TXT
Version: 1.0
Remark

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:

# open file in write mode
with open('file.txt', 'w') as file:
    file.write('This is the first line of the file\n')

# verify the result
with open('file.txt', 'r') as file:
    print(file.read())
This is the first line of the file

Append mode

In append mode 'a', new content is added at the end of the file without overwriting existing content:

# open file in append mode
with open('file.txt', 'a') as file:
    file.write('This is the second line of the file\n')

# verify the result
with open('file.txt', 'r') as file:
    print(file.read())
This is the first line of the file
This is the second line of the file

Writing with the print function

The print() function can write to a file via its file argument. Unlike write(), it appends a newline automatically:

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:

# declare a list of lines
lineas = ['First line\n', 'Second line\n', 'Third line\n']

# write all lines at once
with open('file.txt', 'w') as file:
    file.writelines(lineas)

# verify the result
with open('file.txt', 'r') as file:
    print(file.read())
First line
Second line
Third line

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:

# declare a byte array — ASCII codes for 'Hello'
binarray = bytearray([72, 101, 108, 108, 111])

# write in binary mode
with open('file.bin', 'wb') as file:
    file.write(binarray)

# read back and decode
with open('file.bin', 'rb') as file:
    print(file.read().decode())
Hello

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:

  1. Open the file in 'r' mode and use readlines() to load all lines into a list.
  2. Extract the last element using negative indexing: lines[-1].
  3. 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:

  1. Read all lines from example.txt using readlines().
  2. Extract the last two lines using lines[-2:].
  3. Write them to demo.txt using writelines().
  4. Open and print demo.txt to 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:

  1. Open the file and read all lines using readlines().
  2. 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:

  1. Open the file and iterate over its lines using readlines().
  2. For each line, use 'file' in line.lower() to check for the word.
  3. 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:

  1. Import the datetime class from the datetime module.
  2. Open file.txt in append mode 'a'.
  3. Write a line such as 'Last updated: 2026-05-22 10:30:00\n' using an f-string and datetime.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:

  1. Open tabla.txt in write mode 'w'.
  2. Use a for loop over range(1, 13) to generate each row.
  3. 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:

  1. Use bytearray(b'Python') or list the ASCII codes manually.
  2. Write the bytearray to message.bin using mode 'wb'.
  3. 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:

  1. Collect user input with the built-in input() function.
  2. Open records.txt in append mode 'a' so existing records are preserved.
  3. Write each record field using write() with an f-string.
  4. Control the loop with a while statement checked against the user’s response.

Additional resources