Chapter 13: File Handling in Python
1. Introduction
File handling allows Python programs to store and retrieve data from files. Instead of losing data
when a program ends, files let you save information permanently.
2. Opening Files
Use the open() function with different modes such as read (r), write (w), append (a), and exclusive
creation (x).
file = open("[Link]", "r")
print([Link]())
[Link]()
3. Writing to Files
The write() method stores text into a file. If the file exists in write mode, its previous content is
replaced.
file = open("[Link]", "w")
[Link]("Welcome to Python")
[Link]()
4. Appending Data
Append mode adds new content without deleting existing data.
file = open("[Link]", "a")
[Link]("\nNew line added")
[Link]()
5. Using with Statement
The with statement automatically closes files after use and is the recommended approach.
with open("[Link]", "r") as file:
content = [Link]()
print(content)
6. Reading Methods
Common methods include read(), readline(), and readlines().
with open("[Link]") as f:
print([Link]())
7. Working with CSV Files
CSV files store tabular data. Python's csv module helps read and write them.
import csv
with open("[Link]") as file:
reader = [Link](file)
for row in reader:
print(row)
8. Common Mistakes
- Forgetting to close files. - Using the wrong file mode. - Trying to read a file that does not exist. -
Overwriting data accidentally with write mode.
9. Practice Problems
1. Create a text file and write your name. 2. Read the contents of a file. 3. Append a new line. 4.
Count lines in a file. 5. Count words in a file. 6. Copy contents to another file. 7. Read a CSV file. 8.
Search for a word in a file. 9. Create a log file. 10. Display file size.
10. Sample Solutions
Example implementations:
with open("[Link]", "w") as f:
[Link]("Hello")
with open("[Link]") as f:
print([Link]())
11. Mini Project
Build a Simple Notes Manager that lets users create, view, and append notes stored in a text file.
12. Interview Questions
• What is file handling? • Difference between r, w, and a modes? • Why use with open()? •
Difference between read() and readline()? • What happens if a file does not exist?
13. Summary
File handling enables programs to persist data. Understanding reading, writing, appending, and
safe resource management is essential for real-world applications.