Wednesday, October 15, 2025

File Reading and Writing Basics in Python

 File I/O (Input/Output) allows programs to interact with external files on disk, like saving data to a text file or loading configurations. Python makes this straightforward using the built-in open() function. Always use the context manager (with statement) to automatically close files and handle resources safely.

Key Concepts
  • Opening a File: file = open('filename.txt', 'mode')
    • Modes control access: read-only, write, etc.
  • Reading: Pull data from the file into memory (as strings or lists).
  • Writing: Push data from memory to the file.
  • Closing: Frees resources; with handles this automatically.
  • Error Handling: Use try-except for issues like "file not found."
  • Binary Files: For images/PDFs, add 'b' to mode (e.g., 'rb').
Common Modes
Mode
Description
Use Case
Overwrites?
'r'
Read (default)
Load existing file
No
'w'
Write
Create/overwrite text file
Yes
'a'
Append
Add to end of file
No
'r+'
Read + Write
Modify existing file
No
'rb'/'wb'
Binary Read/Write
Images, executables
Varies
Reading Files
  1. Read Entire File:
    python
    with open('example.txt', 'r') as file:
        content = file.read()  # Returns full string
    print(content)
  2. Read Line by Line:
    python
    with open('example.txt', 'r') as file:
        line = file.readline()  # First line as string
        # Or loop:
        for line in file:  # Iterates over lines
            print(line.strip())  # strip() removes \n
  3. Read All Lines into List:
    python
    with open('example.txt', 'r') as file:
        lines = file.readlines()  # List of strings
    print(lines[0])  # First line
Writing Files
  1. Write String:
    python
    with open('output.txt', 'w') as file:
        file.write("Hello, World!\n")  # \n for new line
  2. Append Text:
    python
    with open('output.txt', 'a') as file:
        file.write("More text!\n")
  3. Write List of Lines:
    python
    lines = ["Line 1\n", "Line 2\n"]
    with open('output.txt', 'w') as file:
        file.writelines(lines)
Full Example: Read, Process, Write
python
# Read from input.txt
with open('input.txt', 'r') as infile:
    data = infile.read().upper()  # Convert to uppercase

# Write processed to output.txt
with open('output.txt', 'w') as outfile:
    outfile.write(data)

print("File processed!")
Tips and Best Practices
  • Encoding: For non-ASCII text, add encoding='utf-8' to open().
  • Exceptions:
    python
    try:
        with open('missing.txt', 'r') as file:
            print(file.read())
    except FileNotFoundError:
        print("File not found!")
  • CSV/JSON: Use csv or json modules for structured data (e.g., import csv; csv.reader()).
  • Performance: For large files, read in chunks: file.read(1024) (bytes at a time).
This covers the essentials for text files. For binary, databases, or another language (e.g., Java's FileWriter), let me know for more!

Lecture Notes: Optimising Numerical Code

Lecture Notes: Optimising Numerical Code Prerequisites: Basic Python programming Understanding of NumPy arrays and vector ...