File Handling in Python
File Handling in Python
What is File Handling?
File handling allows a program to:
- Store data permanently
- Read existing data
- Modify data
- Append new data
- Share data between program executions
Without files:
Program Starts
↓
Data Created
↓
Program Ends
↓
Data Lost
With files:
Program Starts
↓
Read File
↓
Use Data
↓
Write Data
↓
Program Ends
↓
Data Saved
Why Do We Need File Handling?
Real-world applications use files for:
- Saving user data
- Log files
- Configuration files
- Reports
- Database backups
- Game progress
- Student records
Example:
student.txt
John
25
A Grade
Opening a File
Before reading or writing, a file must be opened.
Syntax:
file = open("filename", "mode")
Example:
file = open("data.txt", "r")
File Handling Modes
The mode determines what operation can be performed on the file.
Read Mode (r)
Used to read a file.
Syntax:
file = open("data.txt", "r")
Characteristics:
- File must exist
- Cannot write
- Default mode
Example:
file = open("data.txt", "r")
print(file.read())
file.close()
Write Mode (w)
Used to write data.
Syntax:
file = open("data.txt", "w")
Characteristics:
- Creates file if missing
- Deletes existing content
- Writes new content
Example:
file = open("data.txt", "w")
file.write("Hello")
file.close()
Result:
Hello
Append Mode (a)
Adds data to the end of a file.
Syntax:
file = open("data.txt", "a")
Example:
file = open("data.txt", "a")
file.write("\nPython")
file.close()
Result:
Hello
Python
Exclusive Create Mode (x)
Creates a new file.
Syntax:
file = open("data.txt", "x")
Behavior:
File Exists
↓
Error
Output:
FileExistsError
Read and Write Mode (r+)
Allows reading and writing.
Syntax:
file = open("data.txt", "r+")
Can:
- Read
- Write
Cannot:
- Create missing file
Write and Read Mode (w+)
Allows reading and writing.
Syntax:
file = open("data.txt", "w+")
Characteristics:
- Creates file if needed
- Deletes old content
Append and Read Mode (a+)
Allows reading and appending.
Syntax:
file = open("data.txt", "a+")
Characteristics:
- Creates file if missing
- Appends at end
Binary Modes
Used for:
- Images
- Videos
- PDFs
- Audio files
Read Binary (rb)
file = open("image.jpg", "rb")
Write Binary (wb)
file = open("image.jpg", "wb")
Append Binary (ab)
file = open("image.jpg", "ab")
File Mode Summary Table
| Mode | Read | Write | Create File | Delete Existing Data |
|---|---|---|---|---|
| r | ✓ | ✗ | ✗ | ✗ |
| w | ✗ | ✓ | ✓ | ✓ |
| a | ✗ | ✓ | ✓ | ✗ |
| x | ✗ | ✓ | ✓ | ✗ |
| r+ | ✓ | ✓ | ✗ | ✗ |
| w+ | ✓ | ✓ | ✓ | ✓ |
| a+ | ✓ | ✓ | ✓ | ✗ |
Closing a File
Always close files after use.
Syntax:
file.close()
Example:
file = open("data.txt")
print(file.read())
file.close()
Why Close Files?
Closing:
- Frees memory
- Saves changes
- Releases file lock
Bad:
file = open("data.txt")
Good:
file = open("data.txt")
print(file.read())
file.close()
Reading Files
read()
Reads entire file.
Example:
file = open("data.txt", "r")
content = file.read()
print(content)
file.close()
Suppose file contains:
Hello
Python
World
Output:
Hello
Python
World
read(n)
Reads specific number of characters.
Example:
file = open("data.txt", "r")
print(file.read(5))
file.close()
Output:
Hello
readline()
Reads one line at a time.
Example:
file = open("data.txt")
print(file.readline())
print(file.readline())
file.close()
Output:
Hello
Python
readlines()
Returns list of lines.
Example:
file = open("data.txt")
lines = file.readlines()
print(lines)
file.close()
Output:
['Hello\n', 'Python\n', 'World']
Reading Using Loop
Recommended for large files.
file = open("data.txt")
for line in file:
print(line)
file.close()
Writing Files
write()
Writes text to file.
Example:
file = open("data.txt", "w")
file.write("Python")
file.close()
Writing Multiple Lines
file = open("data.txt", "w")
file.write("Line 1\n")
file.write("Line 2\n")
file.write("Line 3\n")
file.close()
Result:
Line 1
Line 2
Line 3
writelines()
Writes a list of strings.
Example:
file = open("data.txt", "w")
lines = [
"Python\n",
"Java\n",
"C++\n"
]
file.writelines(lines)
file.close()
Appending Files
Append adds data without deleting existing content.
Example
Initial File:
Hello
Program:
file = open("data.txt", "a")
file.write("\nPython")
file.close()
Result:
Hello
Python
Using with Statement
Best practice.
Syntax:
with open("data.txt", "r") as file:
print(file.read())
Advantages:
- Automatically closes file
- Cleaner code
- Safer
File Exception Handling
Files often produce exceptions.
Examples:
- File missing
- No permission
- File already exists
- Invalid path
FileNotFoundError
Example:
file = open("abc.txt", "r")
Output:
FileNotFoundError
Handling FileNotFoundError
try:
file = open("abc.txt", "r")
except FileNotFoundError:
print("File does not exist.")
PermissionError
Example:
try:
file = open("protected.txt", "w")
except PermissionError:
print("Permission denied.")
FileExistsError
Occurs with mode x.
try:
file = open("data.txt", "x")
except FileExistsError:
print("File already exists.")
Complete File Handling Example
try:
with open("student.txt", "r") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("Student file not found.")
except PermissionError:
print("Permission denied.")
except Exception as error:
print("Unexpected error:", error)
Common Beginner Mistakes
Mistake 1: Forgetting to Close File
Bad:
file = open("data.txt")
print(file.read())
Good:
file = open("data.txt")
print(file.read())
file.close()
Better:
with open("data.txt") as file:
print(file.read())
Mistake 2: Using Write Mode Accidentally
Bad:
open("data.txt", "w")
This deletes existing content.
Always verify mode before opening.
Mistake 3: Reading Non-Existent Files
Bad:
file = open("unknown.txt")
Good:
try:
file = open("unknown.txt")
except FileNotFoundError:
print("File missing")
Mistake 4: Forgetting Newline Character
Bad:
file.write("Hello")
file.write("Python")
Output:
HelloPython
Good:
file.write("Hello\n")
file.write("Python\n")
Mistake 5: Not Using with Statement
Bad:
file = open("data.txt")
Good:
with open("data.txt") as file:
print(file.read())
Best Practices
✅ Use with open()
✅ Handle exceptions
✅ Close files properly
✅ Use append mode carefully
✅ Use binary mode for images/videos
✅ Read large files using loops
✅ Keep backups before overwriting files
Homework
Q1
Create a file named:
student.txt
Write:
John
25
A Grade
into it.
Q2
Read the contents of:
student.txt
and display them.
Q3
Append:
Python Developer
to the file.
Q4
Read a file line by line using a loop.
Q5
Handle:
FileNotFoundError
using try-except.
Q6
Create a program using:
with open()
to read a file.
Homework Solutions
Solution 1
with open("student.txt", "w") as file:
file.write("John\n25\nA Grade")
Solution 2
with open("student.txt", "r") as file:
print(file.read())
Solution 3
with open("student.txt", "a") as file:
file.write("\nPython Developer")
Solution 4
with open("student.txt", "r") as file:
for line in file:
print(line)
Solution 5
try:
with open("abc.txt", "r") as file:
print(file.read())
except FileNotFoundError:
print("File not found.")
Solution 6
with open("student.txt", "r") as file:
print(file.read())
Quick Revision
| Topic | Purpose |
|---|---|
| open() | Opens file |
| close() | Closes file |
| read() | Reads whole file |
| readline() | Reads one line |
| readlines() | Reads all lines |
| write() | Writes text |
| writelines() | Writes list of strings |
| r | Read mode |
| w | Write mode |
| a | Append mode |
| x | Create file |
| with open() | Auto close file |
| FileNotFoundError | Missing file |
| PermissionError | No permission |
Summary
File handling allows Python programs to store and retrieve data permanently.
Main operations:
- Open file
- Read file
- Write file
- Append file
- Close file
Important file modes:
r → Read
w → Write
a → Append
x → Create
r+ → Read + Write
w+ → Write + Read
a+ → Append + Read
Always prefer:
with open(...) as file:
because it automatically handles file closing and makes your programs safer and cleaner.