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
  • 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
Important

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:

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

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

# close the 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

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 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:

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 with the 'w' mode. If the file already exists, its contents are overwritten. You can 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

Interenstingly, the print() function can also be used to 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 in each line:

# 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', respectively. 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

  1. Write a program that readsexample.txt and prints the total number of lines it contains.
  2. Write a function that reads the file example.txt and prints a single line specified by the user.
  3. Write a program that reads example.txt line by line and prints every line that contains the word 'John' (case-sensitive).
  4. Write a function that reads example.txt, writes a number of lines specified by the user with a list into a new file demo.txt, and print the contents of demo.txt.
  5. 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.

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().
  4. Control the loop with a while statement checked against the user’s response.

Additional resources