Skip to main content

File Handling, CSV, and Context Managers

1. Reading and Writing Text Files with open()

The open() function is used to open a file for reading, writing, or appending.

Syntax

Common File Modes

Reading a File

Read Line by Line

Writing to a File

Appending to a File


2. CSV Handling Using the csv Module

CSV (Comma-Separated Values) files store tabular data.

Import Module

Reading a CSV File

Output Example

Writing to a CSV File

Writing Multiple Rows

Using DictReader


3. Context Managers (with Statement)

A context manager automatically handles opening and closing files.

Syntax

Advantages

  • Automatically closes the file.
  • Prevents resource leaks.
  • Cleaner and more readable code.
  • Handles exceptions safely.

Without with

With with

No need to call close().

Common File Methods


Example Program

Quick Revision

  • open(): Opens a file.
  • Modes: r (read), w (write), a (append), x (create).
  • csv.reader(): Reads CSV files.
  • csv.writer(): Writes CSV files.
  • csv.DictReader(): Reads CSV rows as dictionaries.
  • with statement: Automatically closes files and makes code safer and cleaner.