csaccept.com is a computer awareness website dedicated to providing reliable and easy-to-understand information about computer technology and digital safety. The website focuses on educating students, beginners, and general users about computer basics, cyber security, emerging technologies, and practical IT skills. Through informative articles, quizzes, and real-life examples, csaccept.com aims to increase digital literacy and help users stay safe and confident in today’s technology-driven world.
Facebook ………………..
Instagram ……………..
Twitter ( X ) ……………..
YouTube
Python File Handling :
File handling is an important part of programming. It allows programs to store data permanently, read saved data, and modify existing data.
In Python, file handling is simple, powerful, and widely used in real-world applications such as logs, reports, databases, configuration files, and more.
1. Introduction to File Input/Output (I/O)
File Input/Output (I/O) refers to the process of reading data from files and writing data to files.
Python allows you to work with external files stored on disk, such as:
- Text files (.txt)
- CSV files (.csv)
- JSON files (.json)
- Images, audio, video (Binary files)
Why File Handling is Important
- Store data permanently
- Read previously saved data
- Generate reports
- Log program activities
- Data processing & automation
2. Opening and Closing Files
Before performing any operation on a file, you must open it.
Python provides the built-in function:
open(filename, mode)
Parameters
- filename → File name or path
- mode → Purpose of opening the file
Common File Modes
| Mode | Description |
|---|---|
| r | Read (default) |
| w | Write (overwrites file) |
| a | Append (adds data) |
| x | Create new file |
| rb | Read binary |
| wb | Write binary |
Example: Open and Close File
file = open("example.txt", "r") # Open file in read mode
file.close() # Close file
Why Close File?
- Releases system memory
- Prevents file corruption
- Good programming practice
3. Reading and Writing Text Files
Python provides multiple methods to read and write text files.
Reading Methods
3.1 Read entire file → read()
file = open("input.txt", "r")
data = file.read()
print(data)
file.close()
3.2 Read one line → readline()
file = open("input.txt", "r")
print(file.readline())
file.close()
3.3 Read all lines → readlines()
file = open("input.txt", "r")
lines = file.readlines()
print(lines)
file.close()
Writing to File → write()
file = open("output.txt", "w")
file.write("Hello, World!")
file.close()
Note: "w" mode deletes previous content.
Appending Data → "a"
file = open("output.txt", "a")
file.write("\nNew Line Added")
file.close()
4. Working with Binary Files
Binary files store raw data (non-readable) such as:
- Images (.jpg, .png)
- Audio (.mp3)
- Video (.mp4)
- Executable files
To work with binary files, use:
"rb"→ Read Binary"wb"→ Write Binary
Example: Copy Image File
source = open("photo.jpg", "rb")
data = source.read()
source.close()
dest = open("copy.jpg", "wb")
dest.write(data)
dest.close()
5. Exception Handling in File Operations
File operations may produce errors such as:
- File not found
- Permission denied
- Disk full
- File already exists
Python uses Exception Handling to manage errors safely.
Try-Except-Finally Structure
try:
file = open("example.txt", "r")
content = file.read()
print(content)
except IOError:
print("An error occurred while handling the file.")
finally:
file.close()
Purpose
| Block | Use |
|---|---|
| try | Code that may cause error |
| except | Handles error |
| finally | Always executes (used to close file) |
Best Practice: Using with Statement
Python automatically closes the file using with.
with open("example.txt", "r") as file:
data = file.read()
print(data)
✔ No need to manually close file
✔ Safer & cleaner code
Real-World Example: Student Record System
# Writing student data
with open("students.txt", "w") as file:
file.write("Name: Rahul\n")
file.write("Course: BCA\n")
file.write("Marks: 85\n")
# Reading student data
with open("students.txt", "r") as file:
print(file.read())
Common Errors in File Handling
| Error | Cause |
|---|---|
| FileNotFoundError | File does not exist |
| PermissionError | No permission |
| IsADirectoryError | Trying to open folder |
| UnicodeDecodeError | Wrong encoding |
Summary :
- File I/O = Reading + Writing files
- Use
open()to open files - Always close files (or use
with) - Use different modes (
r,w,a,rb,wb) - Handle errors using
try-except - Use binary mode for images/audio
- File handling is widely used in real-world applications
Short Questions & Answers
Q1. What is file handling in Python?
Answer:
File handling in Python allows reading data from files and writing data to files stored on disk using file I/O operations.
Q2. What is File I/O?
Answer:
File Input/Output (I/O) refers to the process of reading data from files and writing data to files.
Q3. Which function is used to open a file in Python?
Answer:
The built-in open() function is used to open a file.
Q4. What are file modes?
Answer:
File modes specify how a file is opened, such as read, write, append, or binary mode.
Q5. Write any four file modes in Python.
Answer:r, w, a, rb
Q6. What does "r" mode do?
Answer:
It opens a file for reading only.
Q7. What does "w" mode do?
Answer:
It opens a file for writing and deletes existing content.
Q8. What is the use of close() method?
Answer:
It closes the file and releases system resources.
Q9. What is the use of read() method?
Answer:
It reads the entire contents of a file as a string.
Q10. What does readline() do?
Answer:
It reads one line from a file at a time.
Q11. What does readlines() return?
Answer:
It returns all lines of a file as a list.
Q12. Which method is used to write data to a file?
Answer:
The write() method is used.
Q13. What is a binary file?
Answer:
A binary file stores non-human-readable data such as images, audio, and video.
Q14. Which mode is used to read binary files?
Answer:rb mode.
Q15. Why is exception handling important in file operations?
Answer:
It prevents program crashes and handles file-related errors gracefully.
Q16. Which block is used to handle errors?
Answer:
The except block.
Q17. What is the purpose of the finally block?
Answer:
It ensures the file is closed even if an exception occurs.
Q18. Name the best practice for file handling in Python.
Answer:
Using the with statement.
Q19. Does with statement automatically close files?
Answer:
Yes, it automatically closes the file.
Q20. Write one real-life use of file handling.
Answer:
Storing student records or log files.
MCQ Quiz –
1. File I/O stands for:
A) File Input Only
B) File Output Only
C) File Input and Output
D) File Internal Operation
✅ Answer: C
2. Which function is used to open a file?
A) file()
B) open()
C) read()
D) write()
✅ Answer: B
3. Which mode opens a file for reading?
A) w
B) a
C) r
D) x
✅ Answer: C
4. Which mode deletes existing file content?
A) r
B) a
C) w
D) rb
✅ Answer: C
5. Which method reads the whole file?
A) readline()
B) read()
C) readlines()
D) write()
✅ Answer: B
6. What does readlines() return?
A) String
B) Integer
C) List
D) Tuple
✅ Answer: C
7. Which method is used to write data?
A) write()
B) read()
C) open()
D) close()
✅ Answer: A
8. Which mode is used for appending data?
A) w
B) r
C) a
D) x
✅ Answer: C
9. Binary files are opened using:
A) t
B) b
C) rb / wb
D) x
✅ Answer: C
10. Which file contains raw data?
A) Text file
B) Binary file
C) CSV file
D) HTML file
✅ Answer: B
11. Which block handles errors?
A) try
B) except
C) finally
D) raise
✅ Answer: B
12. Which block always executes?
A) try
B) except
C) finally
D) error
✅ Answer: C
13. Which error occurs when file is missing?
A) ValueError
B) IOError
C) TypeError
D) SyntaxError
✅ Answer: B
14. What does with open() do?
A) Opens file permanently
B) Does not close file
C) Automatically closes file
D) Deletes file
✅ Answer: C
15. Which is the safest way to handle files?
A) open() only
B) try only
C) with statement
D) print()
✅ Answer: C

