Andromeda
Note

File Handling (Python)

Definition

The process of reading from and writing to external files, allowing a program to persist data beyond its execution time and analyze large external datasets.

Why It Matters

Without file handling, a program is a “ghost” that forgets everything as soon as it stops running. It is the fundamental skill required to build “real-world” software that manages data at scale. Mastering it allows you to automate the “heavy lifting” of data analysis, ensuring that your insights are persistent, shareable, and verifiable across different systems.

Core Concepts

  • The File Lifecycle:
    1. open(): Returns a file object. Modes: 'r' (read), 'w' (write/overwrite), 'a' (append). Use Binary Mode ('rb', 'wb') for non-plaintext files like PDFs or images.
    2. Read/Write: Using .read(), .readlines(), or .write().
    3. close(): Essential to free memory (or use with).
  • Example Usage:
# Writing to a file using 'with' (auto-closes)
with open('hello.txt', 'w') as f:
    f.write('Hello from Python!\n')

# Reading from a file
with open('hello.txt', 'r') as f:
    content = f.read()
    print(content)
  • High-Level Shell Utilities (shutil):
    • shutil.copy(src, dst): Copies a single file.
    • shutil.copytree(src, dst): Copies an entire directory tree.
    • shutil.move(src, dst): Moves or renames files/folders.
    • shutil.rmtree(path): Permanent deletion of a folder and all its contents.
  • The “Permanence” Warning: Functions like os.unlink() and shutil.rmtree() delete files instantly and permanently (bypassing the Recycle Bin).
  • Safe Deletion: Use the send2trash module to move files to the system’s trash/recycle bin instead of permanent deletion.
  • Tactical Pattern: The Dry Run: Before running destructive code, comment out the deletion line and replace it with print(f"Would delete: {filename}") to verify targets.

Connected Concepts