Codectionary / Developer documentation / Python

File Handling

Python's built-in open() function reads from and writes to files on disk. Using it with the 'with' statement (a context manager) ensures the file is automatically closed when the block ends, even if an error occurs - this is the recommended way to work with files. The mode argument controls behavior: 'r' for reading, 'w' for writing (overwriting), 'a' for appending, among others.

Syntax

with open(filepath, mode) as f:\n    # work with f

Examples

Reading a File

Reading the entire contents of a file at once.

with open("notes.txt", "r") as f:
    content = f.read()

print(content)
# File is automatically closed here, even if an error occurred

Writing to a File

Creating or overwriting a file with new content.

with open("output.txt", "w") as f:
    f.write("Line one\n")
    f.write("Line two\n")

# The file now contains exactly those two lines - any previous content is gone

Appending to a File

Adding new content to the end of an existing file without erasing what's already there.

with open("log.txt", "a") as f:
    f.write("New log entry\n")

# Existing content in log.txt is preserved, new line added at the end

Reading Line by Line

Iterating over a file object processes it one line at a time, which is memory-efficient for large files.

with open("data.csv", "r") as f:
    for line in f:
        print(line.strip())  # .strip() removes the trailing newline

Best practices

  • Always use 'with open(...) as f:' instead of manually calling open() and close() - it guarantees the file closes even if an exception occurs
  • Use mode 'r' for reading, 'w' to overwrite/create, and 'a' to append - mixing these up can accidentally erase data
  • Iterate directly over a file object (for line in f:) rather than reading the whole file into memory when processing large files line by line
  • Specify the encoding explicitly (encoding='utf-8') when working with text files that may contain non-ASCII characters

At a glance

Purpose
Scripting and general-purpose applications
File extension
.py
Runs in
Python interpreter
Usually used with
Python standard library and packages

Specifications & further reading

Related Python documentation

import
The import statement brings code from another module or package into the current file, letting you reuse functions, classes, and variables defined elsewhere - whether from Python's standard library, a third-party package, or your own project files. Python offers several import styles: importing an entire module, importing specific names directly, and renaming imports with 'as' to avoid naming conflicts or shorten long module names.
if __name__ == '__main__'
Every Python module has a built-in __name__ variable. When a file is run directly, __name__ is set to '__main__'; when the same file is imported into another module, __name__ is set to the module's actual name instead. The if __name__ == '__main__': guard lets you write code that only runs when the file is executed directly, not when it's imported elsewhere - essential for writing reusable modules that also work as standalone scripts.
os Module
The os module provides functions for interacting with the operating system - working with file paths, listing directory contents, creating and removing folders, and reading environment variables. Its os.path submodule (or the more modern pathlib alternative) handles cross-platform file path manipulation, so your code works correctly on Windows, macOS, and Linux without hardcoding path separators.
datetime Module
The datetime module provides classes for working with dates and times - creating them, formatting them for display, parsing them from text, and performing date arithmetic. The datetime class combines both a date and a time, while timedelta represents a duration, letting you add or subtract time spans from a date. strftime() formats a datetime as text, and strptime() parses text back into a datetime.