B2.5.1

Construct code to perform file-processing operations

A file is a named collection of data stored on secondary storage (e.g., hard drive, SSD). Files allow data to persist after a program ends — unlike…

4 min read666 words

What is a File?

A file is a named collection of data stored on secondary storage (e.g., hard drive, SSD). Files allow data to persist after a program ends — unlike variables in RAM, which are lost when the program exits.

File Paths

TermMeaning
Absolute pathFull path from the root of the file system — e.g., C:\Users\Michael\data.txt
Relative pathPath relative to the current working directory — e.g., data/sample.txt

File Modes

Before opening a file, you must specify the mode — what operation you intend to perform.

ModeCharacterDescriptionCreates file?Overwrites?
ReadrRead from file (default)❌ No❌ No
WritewWrite to file✅ Yes✅ Yes (truncates)
AppendaAppend to end of file✅ Yes❌ No
Read+Writer+Read and write❌ No❌ No
Write+Readw+Write and read✅ Yes✅ Yes
Append+Reada+Append and read✅ Yes❌ No

Opening and Closing Files

The Old Way (Manual)

file = open("data.txt", "r")
content = file.read()
file.close()

The with statement automatically closes the file when the block exits, even if an exception occurs:

with open("data.txt", "r") as file:
    content = file.read()
# File is automatically closed here
with open("data.txt", "w") as file:
    file.write("Hello, World!")
# File is automatically closed here

Reading Files

Read Entire File as a String

with open("data.txt", "r") as file:
    content = file.read()
print(content)

Read Specific Number of Characters

with open("data.txt", "r") as file:
    first_10 = file.read(10)   # Read first 10 characters

Read One Line at a Time

with open("data.txt", "r") as file:
    line1 = file.readline()    # Read the first line (includes '\n')
    line2 = file.readline()    # Read the second line

Read All Lines into a List

with open("data.txt", "r") as file:
    lines = file.readlines()   # Returns a list of all lines

for line in lines:
    print(line, end="")

Iterate Line by Line (Memory Efficient)

with open("data.txt", "r") as file:
    for line in file:
        print(line, end="")

Writing Files

Write a String (Overwrites)

with open("output.txt", "w") as file:
    file.write("First line\n")
    file.write("Second line\n")

Write Multiple Lines (writelines)

lines = ["Line 1\n", "Line 2\n", "Line 3\n"]

with open("output.txt", "w") as file:
    file.writelines(lines)

Append to a File

with open("output.txt", "a") as file:
    file.write("Appended line\n")

Common Exceptions in File Processing

ExceptionCause
FileNotFoundErrorTrying to read a file that doesn’t exist
PermissionErrorNo permission to read/write the file
IsADirectoryErrorPath points to a directory, not a file
UnicodeDecodeErrorFile cannot be decoded with the given encoding

Handling File Exceptions

try:
    with open("missing.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("File does not exist.")
except PermissionError:
    print("You do not have permission to access this file.")
else:
    print("File read successfully.")

Best Practices Summary

PracticeWhy it matters
Always use with statementGuarantees file closure, even on exceptions
Use encoding="utf-8"Handles international characters correctly
Check if file exists before readingPrevents FileNotFoundError crashes
Avoid mode w when preserving dataUse a to append, not overwrite

Start typing to search all published objectives.