๐ Lesson 15: Python File Handling – Read & Write Files
Welcome to Lesson 15! Today we’ll learn about file handling in Python. Files allow your programs to store data permanently, read data from text files, or write results to a file.
⭐ What You Will Learn in This Lesson
- Open, read, write, and append files
- Use the
withstatement for safe file handling - Work with files line by line
- Understand different file modes
- Save and manage data in your programs
๐ฅ Who Is This Lesson For?
- Beginners learning to store program data
- Students working on projects requiring file input/output
- Anyone building interactive programs or logs
๐ฆ Opening a File
Use the open() function to work with files. The syntax is:
file = open("example.txt", "mode")
- "r" – read (default)
- "w" – write (overwrite)
- "a" – append (add to end)
- "r+" – read and write
๐งฉ 1. Reading Files
# Read entire file
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
# Read line by line
file = open("example.txt", "r")
for line in file:
print(line.strip())
file.close()
๐งฉ 2. Writing Files
file = open("example.txt", "w")
file.write("Hello, Python!\n")
file.write("File handling is fun.")
file.close()
๐งฉ 3. Appending Files
file = open("example.txt", "a")
file.write("\nAdding a new line.")
file.close()
๐งฉ 4. Using with Statement
The with statement automatically closes the file for you:
with open("example.txt", "r") as file:
print(file.read())
with open("example.txt", "a") as file:
file.write("\nThis is safe and easy!")
๐งฉ 5. Why File Handling Matters
- Store data permanently
- Read configuration or input files
- Write logs or results
- Essential for projects, data science, and apps
๐งช Practice
- Create a text file and write your name and age into it.
- Read the file and print its content line by line.
- Append a new hobby to the file.
- Use the
withstatement to safely read and write files. - Experiment with different file modes (
r, w, a, r+) and observe results.
❌ Common Mistakes
- Forgetting to close files when not using
with - Overwriting data unintentionally with
wmode - Trying to read a file that doesn’t exist without
try/except
❓ Frequently Asked Questions (FAQ)
1. Can I read large files line by line?
Yes, using a loop: for line in file: reads one line at a time.
2. What happens if I write to a file that already exists?
Using w will overwrite the file. Use a to append instead.
3. Why use the with statement?
It automatically closes the file even if errors occur, making code safer.
Comments
Post a Comment