File handling is an important concept in Python that allows you to create, read, write, update, and delete files. It helps you store data permanently in your system instead of keeping it only in memory.
Python provides built-in functions to work with files easily.
In this tutorial, you will learn everything about file handling in Python with clear examples.
What is File Handling?
File handling means performing operations on files such as:
- Creating a file
- Reading data
- Writing data
- Appending data
- Deleting files
File Opening Modes in Python
Python provides different modes to open files:
| Mode | Description |
|---|---|
| 'r' | Read (default) |
| 'w' | Write (overwrite) |
| 'a' | Append |
| 'x' | Create file |
| 'rb' | Read binary |
| 'wb' | Write binary |
1. Opening a File
Syntax:
file = open("example.txt", "r")2. Reading a File
The read() method reads the entire file content.
Example:
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()Explanation:
- Opens file in read mode
- Reads all content
- Closes file after use
3. Reading Line by Line
Example:
file = open("example.txt", "r")
for line in file:
print(line)
file.close()4. Writing to a File
The w mode writes data and overwrites existing content.
Example:
file = open("example.txt", "w")
file.write("Hello Python File Handling!")
file.close()5. Appending to a File
The a mode adds new content without deleting old data.
Example:
file = open("example.txt", "a")
file.write("\nThis is new line added.")
file.close()6. Creating a New File
The x mode creates a new file.
Example:
file = open("newfile.txt", "x")
file.write("This is a new file.")
file.close()7. Using with Statement (Best Practice)
The with statement automatically closes the file.
Example:
with open("example.txt", "r") as file:
content = file.read()
print(content)Advantage:
- No need to call
close() - Safer and cleaner code
8. Checking if File Exists
Example:
import os
if os.path.exists("example.txt"):
print("File exists")
else:
print("File not found")9. Deleting a File
Example:
import os
os.remove("example.txt")Real-World Example: Save User Data
name = "John"
age = 25
with open("user.txt", "w") as file:
file.write(f"Name: {name}\nAge: {age}")Real-World Example: Log System
with open("log.txt", "a") as file:
file.write("User logged in\n")File Handling Methods Summary
| Method | Description |
| open() | Opens a file |
| read() | Reads file content |
| write() | Writes data |
| append() | Adds data |
| close() | Closes file |
| with | Auto close file |
| os.remove() | Deletes file |
Common Mistakes
Mistake 1: Forgetting to close file
❌ Wrong:
file = open("example.txt", "r")
print(file.read())✔ Always close file or use with
Mistake 2: Using wrong mode
open("file.txt", "r") # File doesn't exist✔ Causes FileNotFoundError
Mistake 3: Overwriting data accidentally
open("file.txt", "w")✔ This deletes existing content
Safe File Handling Example
with open("data.txt", "a") as file:
file.write("Safe append operation\n")Conclusion
File handling in Python is essential for working with data storage and real-world applications.
You learned:
- How to open, read, write, and append files
- Different file modes
- Safe file handling using
with - Deleting and checking files
- Real-world examples
Mastering file handling helps you build powerful applications like log systems, data storage tools, and automation scripts.


0 Comments