Python File Handling Notes - Class 12
What is a File?
A file is used to store data permanently on a computer. Python can open, read, write, and close files.
Types of Files
- Text File (.txt): Human-readable text.
- Binary File (.dat/.bin): Data in binary format, not human-readable.
- CSV File (.csv): Data stored in table form, comma-separated.
File Paths
Absolute Path: Full path from root (e.g., C:\Users\User\file.txt)
Relative Path: Path from current directory (e.g., files\data.txt)
Opening Text File
file = open('example.txt', 'r')
Modes for Text Files
'r': Read
'w': Write (overwrites)
'a': Append
'r+': Read + Write
'w+': Write + Read
'a+': Append + Read
Using 'with' Statement
with open('example.txt', 'r') as file:
data = file.read()
Writing to Text File
file.write('Hello')
file.writelines(['Line1\n', 'Line2\n'])
Python File Handling Notes - Class 12
Reading from Text File
file.read() - All
file.readline() - One line
file.readlines() - List of lines
seek() and tell()
file.tell() - Get position
file.seek(0) - Go to start
Modifying Text File
Read lines, change data, write back using writelines()
Binary File Basics
Used for storing Python objects
Need 'pickle' module
Writing to Binary File
import pickle
with open('data.dat', 'wb') as f:
pickle.dump(obj, f)
Reading from Binary File
with open('data.dat', 'rb') as f:
obj = pickle.load(f)
CSV Files
Used to store table-like data using commas
Writing to CSV
import csv
Python File Handling Notes - Class 12
with open('data.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['Name', 'Age'])
Reading from CSV
with open('data.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
print(row)