Python File Handling Notes (Basic to Pro)
Introduction to File Handling
File handling allows us to store data permanently in files, so we can use the data later. In Python,
Why File Handling is Important in Real Life?
1. Storing student records in colleges.
2. Saving employee details in companies.
3. Maintaining logs (e.g., login records, transaction history).
4. Handling large datasets (e.g., CSV, JSON files).
5. Storing chat messages in apps like WhatsApp.
Opening a File
Python provides the open() function.
Syntax: open(filename, mode)
Modes:
'r' → Read
'w' → Write (overwrites existing content)
'a' → Append (adds content without deleting old data)
'b' → Binary mode (for images, videos)
'x' → Create new file
Example 1: Writing to a File
file = open('[Link]', 'w')
[Link]('Hello Students!')
[Link]()
Example 2: Reading from a File
file = open('[Link]', 'r')
data = [Link]()
print(data)
[Link]()
Example 3: Appending to a File
file = open('[Link]', 'a')
[Link]('\nThis is an appended line.')
[Link]()
Using 'with' Statement (Best Practice)
with open('[Link]', 'r') as file:
data = [Link]()
print(data)
Advantage: No need to close() file explicitly.
Working with Real Data (CSV Example)
import csv
with open('[Link]', 'w', newline='') as file:
writer = [Link](file)
[Link](['ID', 'Name', 'Marks'])
[Link]([1, 'Rahul', 85])
[Link]([2, 'Anita', 90])
with open('[Link]', 'r') as file:
reader = [Link](file)
for row in reader:
print(row)
File Handling in Daily Life Applications
1. College portals store student assignments in text files.
2. Banking systems save transaction logs.
3. E-commerce sites maintain order records in files.
4. Social media apps save chat backups in files.
5. Data scientists save models and datasets in files.