Python File Handling: Read, Write, Append, Delete Files
File handling is one of the most practical skills in Python programming. It allows your programs to interact with the computer’s storage — whether you’re saving logs, storing user data, reading configurations, or processing datasets. Without file handling, most real-world applications would not be possible.
Opening a File in Python
Python provides the built-in open()
function to work with files. The general syntax is:
f = open("filename.txt", "mode")
File modes explained:
Mode | Description |
---|---|
"r" | Read (default). Error if file doesn’t exist. |
"w" | Write. Creates a new file or overwrites existing content. |
"a" | Append. Adds content to the end of the file. |
"x" | Create. Fails if file already exists. |
"t" | Text mode (default). |
"b" | Binary mode (images, videos, etc.). |
Reading Files
Use "r"
mode to read an existing file. Python provides three methods:
Method | Description |
---|---|
read() | Reads the whole file as a single string. |
readline() | Reads one line at a time. |
readlines() | Reads all lines into a list. |
f = open("example.txt", "r")
print(f.read())
f.close()
Writing to Files
Use "w"
mode to create or overwrite a file:
f = open("example.txt", "w")
f.write("Hello, Python file handling!\n")
f.write("This file now has two lines.")
f.close()
"w"
mode erases any existing file content.Appending to Files
Appending adds new content without removing existing data. Use "a"
mode:
f = open("example.txt", "a")
f.write("\nThis new line is appended.")
f.close()
Deleting Files
Use the os
module to delete files safely:
import os
if os.path.exists("example.txt"):
os.remove("example.txt")
print("File deleted successfully.")
else:
print("The file does not exist.")
Using the with
Statement
The with
statement is recommended because it closes the file automatically:
with open("example.txt", "r") as f:
data = f.read()
print(data)
with
for cleaner, safer file handling.Real-World Uses of File Handling
- Storing logs of applications
- Saving user preferences and settings
- Reading datasets (CSV, JSON)
- Creating configuration files
Exercise
Try it yourself:
- Create a file
students.txt
and write 3 names. - Append 2 more names.
- Read and print all names.
- Delete the file safely using
os.remove()
.
FAQ
What’s the difference between "w" and "a" mode?
"w" overwrites the file, while "a" adds content to the end.
How do I handle binary files?
Use "rb"
or "wb"
mode for reading/writing binary files (e.g., images).
Can I open multiple files at once?
Yes, use multiple with open()
statements or nested context managers.
Conclusion
Python file handling is a fundamental skill for any developer. By mastering read, write, append, and delete operations, you make your programs more powerful and practical. Keep practicing with small projects like loggers, note-taking apps, or dataset readers — they will sharpen your real-world coding skills.
📌Related Posts
- Python Programming: A Beginner’s Guide
- Python Variables
- Python Data Types
- Python Strings
- Python Operators
- Python Lists
- Python Tuples
- Python Sets
- Python Dictionaries
- Python If...Else Statements and Conditions
- Python Match Statement
- Python Functions
- Python Lambda
- Python Arrays
- Python Classes & Objects
- Python Inheritance
- Python Iterators
- Python Polymorphism
- Python Scope
- Python Modules
- Python Datetime
- Python Math
- Python Exception Handling
Continue Learning: Explore more beginner-friendly topics and practice materials in our Programming Resource Hub.
0 Comments