Skip to content

open() Function Complexity

The open() function opens a file and returns a file object, allowing reading, writing, and manipulation of file contents.

Complexity Reference

Operation Time Space Notes
open(filename) O(1)* O(1) System call; * may vary with filesystem
file.read() O(n) O(n) n = file size
file.readline() O(k) O(k) k = line length
file.readlines() O(n) O(n) n = file size
file.write(data) O(k) O(1)* k = data length; * buffered, actual I/O varies
file.close() O(1) O(1) Flush and close
for line in file: O(n) O(1) n = file size (lazy iteration)

Opening Files

Basic File Operations

# Open for reading - O(1) system call
file = open('data.txt', 'r')  # O(1)
content = file.read()         # O(n) - read entire file
file.close()                  # O(1)

# Or use context manager (recommended)
with open('data.txt', 'r') as file:  # O(1)
    content = file.read()             # O(n)
# File automatically closed - O(1)

File Modes

# Read mode (default) - O(1)
file = open('file.txt', 'r')      # O(1) - text mode

# Binary mode - O(1)
file = open('file.bin', 'rb')     # O(1) - binary read

# Write mode - O(1)
file = open('output.txt', 'w')    # O(1) - text write

# Append mode - O(1)
file = open('log.txt', 'a')       # O(1) - append to end

# Read/Write - O(1)
file = open('data.txt', 'r+')     # O(1) - read and write

Reading File Contents

Read Methods

with open('data.txt', 'r') as file:
    # Read entire file - O(n)
    content = file.read()  # O(file_size)

    # Read line by line - O(k) per line
    file.seek(0)  # O(1) - go to start
    line = file.readline()  # O(k) - k = line length

    # Read all lines into list - O(n)
    file.seek(0)
    lines = file.readlines()  # O(n) - creates list

    # Iterate lines (memory efficient) - O(1) per line
    file.seek(0)
    for line in file:  # O(1) per iteration, lazy
        process(line)

Reading Line by Line (Memory Efficient)

# Best for large files: iterate without loading all
with open('largefile.txt', 'r') as file:
    for line in file:  # O(1) per line, O(1) memory
        # Process one line at a time
        print(line.strip())

# vs. loading all at once - O(n) memory
with open('largefile.txt', 'r') as file:
    all_lines = file.readlines()  # O(n) memory!
    for line in all_lines:        # Still O(1) per iteration
        print(line.strip())

Writing to Files

Write Operations

# Write string - O(k) where k = string length
with open('output.txt', 'w') as file:
    file.write('Hello')  # O(5)
    file.write(' ')      # O(1)
    file.write('World')  # O(5)

# Write multiple lines - O(n)
lines = ['Line 1\n', 'Line 2\n', 'Line 3\n']
with open('output.txt', 'w') as file:
    file.writelines(lines)  # O(n)

# Write with formatting - O(n)
with open('output.txt', 'w') as file:
    for i, item in enumerate(items):
        file.write(f"{i}: {item}\n")  # O(k) per write

File Iteration

Iterating Lines

# Most efficient: lazy line iteration - O(1) memory per line
with open('data.txt', 'r') as file:
    for line in file:  # O(1) per iteration
        # Process line
        process(line)

# This is more efficient than:
with open('data.txt', 'r') as file:
    for line in file.readlines():  # O(n) memory upfront!
        process(line)

# For files with millions of lines:
# - Iteration: O(n) time, O(1) memory
# - readlines(): O(n) time, O(n) memory

File Positioning

Seek and Tell

with open('data.txt', 'rb') as file:
    # Get current position - O(1)
    pos = file.tell()  # Usually 0 at start

    # Read some bytes - O(k)
    data = file.