Working with Files
File Handling Concepts Table
1
with open()
for file handling
Reading/writing files safely, ensuring proper closure
Automatically closes files
Cleaner code
Less prone to errors
Limited to scope of
with
block
2
File Modes ('r'
, 'w'
, 'a'
)
Choose based on whether you're reading, writing, or appending
Flexible modes
Supports text and binary modes
'r+'
allows read/write
'w'
can overwrite dataWrong mode may raise error
3
Reading large files efficiently
Log files, datasets – when full file can’t be loaded into memory
Memory efficient
Great for huge files
Slightly more logic needed
4
File Reading Techniques
Different ways of reading based on need (whole, lines, line by line)
Multiple options for use cases
readlines()
useful for processing all at once
read()
andreadlines()
can be memory-heavy for big files
5
Context Managers
Safe file and resource handling using with
Auto resource management
Prevents file leaks
Readable and Pythonic
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