File Handling
File handling is one of the MOST important concepts in Python.
It allows your program to create, read, update, and delete files.
Python supports different file types:
- Text files (.txt)
- CSV files (.csv)
- JSON files (.json)
- Binary files (.bin)
- Others (images, pdf, etc.)
1. Types of File Modes
| Mode | Meaning |
|---|---|
"r" |
Read mode (file must exist) |
"w" |
Write mode (creates new file, deletes old content) |
"a" |
Append mode (adds data at end) |
"r+" |
Read + Write |
"w+" |
Write + Read (deletes old content) |
"a+" |
Append + Read |
"b" |
Binary mode (images, videos) |
You can combine modes:
"rb" → read binary
"wb" → write binary
2. Reading a File
Example file: data.txt
Hello Python
Welcome to File Handling
Read entire file
f = open("data.txt", "r")
print(f.read())
f.close()
Read line by line
f = open("data.txt", "r")
for line in f:
print(line)
f.close()
Read first 10 characters
f = open("data.txt", "r")
print(f.read(10))
f.close()
3. Writing to a File
Rewrite the file (old content removed)
f = open("data.txt", "w")
f.write("This is day 22 content.\nLearning Python!")
f.close()
4. Append to a File
Add new lines without deleting old data
f = open("data.txt", "a")
f.write("\nAdding new content at the end.")
f.close()
5. Using with (Best Practice)
The file automatically closes — no need to call close().
Reading using with
with open("data.txt", "r") as f:
print(f.read())
Writing using with
with open("data.txt", "w") as f:
f.write("Hello from with block!")
6.Read File Into a List
Each line becomes list element.
with open("data.txt", "r") as f:
lines = f.readlines()
print(lines)
Example output:
['Hello Python\n', 'Welcome to File Handling']
7. Writing a List to a File
lines = ["Apple\n", "Banana\n", "Cherry\n"]
with open("fruits.txt", "w") as f:
f.writelines(lines)
8.Checking File Exists
Using os module:
import os
if os.path.exists("data.txt"):
print("File exists")
else:
print("File not found")
9. Delete a File
import os
os.remove("data.txt")
this permanently deletes the file
10. File Pointer Methods
| Method | Use |
|---|---|
tell() |
Shows current cursor position |
seek() |
Move cursor to a position |
Example
f = open("data.txt", "r")
print(f.tell()) # Position
print(f.read(5)) # Reads 5 chars
f.seek(0) # Move to start
print(f.read())
f.close()
11.Handling Errors in File Operations
Try–Except
try:
f = open("abc.txt")
print(f.read())
except FileNotFoundError:
print("File does not exist!")
12.File Handling Mini-Programs
Program 1: Count number of lines
with open("data.txt", "r") as f:
count = len(f.readlines())
print("Total lines:", count)
Program 2: Count words in file
with open("data.txt", "r") as f:
text = f.read()
words = text.split()
print("Total words:", len(words))
Program 3: Copy one file to another
with open("data.txt", "r") as f1:
with open("copy.txt", "w") as f2:
f2.write(f1.read())
Top comments (0)