Working with Files

File Handling Concepts Table

SI
Section
Usage Scenario
Pros
Cons

1

with open() for file handling

Reading/writing files safely, ensuring proper closure

  1. Automatically closes files

  2. Cleaner code

  3. Less prone to errors

  1. Limited to scope of with block

2

File Modes ('r', 'w', 'a')

Choose based on whether you're reading, writing, or appending

  1. Flexible modes

  2. Supports text and binary modes

  3. 'r+' allows read/write

  1. 'w' can overwrite data

  2. Wrong mode may raise error

3

Reading large files efficiently

Log files, datasets – when full file can’t be loaded into memory

  1. Memory efficient

  2. Great for huge files

  1. Slightly more logic needed

4

File Reading Techniques

Different ways of reading based on need (whole, lines, line by line)

  1. Multiple options for use cases

  2. readlines() useful for processing all at once

  1. read() and readlines() can be memory-heavy for big files

5

Context Managers

Safe file and resource handling using with

  1. Auto resource management

  2. Prevents file leaks

  3. Readable and Pythonic

  1. Can't use file object after exiting with block


Code Sample

with open('example.txt', 'r') as file:
    data = file.read()
    print(data)

Last updated