1. Introduction

File handling is one of the most important skills in Python. Almost every real-world application needs to read from or write to a file. Python makes file handling simple with built-in functions and context managers.
2. Opening and Closing Files
To work with a file, you first need to open it using the built-in open()
function.
# Open a file for reading
file = open("example.txt", "r")
content = file.read()
print(content)
file.close() # Always close the file
File Modes in Python:
Mode | Description |
---|---|
"r" | Read (default) – file must exist |
"w" | Write – creates new file or overwrites existing |
"a" | Append – adds new content without deleting old data |
"x" | Create – fails if file already exists |
"b" | Binary mode (e.g., images, videos) |
"t" | Text mode (default) |
3. Reading Files
Python offers multiple ways to read a file:
# Read entire file
with open("example.txt", "r") as f:
data = f.read()
print(data)
# Read line by line
with open("example.txt", "r") as f:
for line in f:
print(line.strip())
# Read specific number of characters
with open("example.txt", "r") as f:
partial = f.read(10) # first 10 characters
print(partial)
4. Writing to Files
# Write (overwrites file if it exists)
with open("example.txt", "w") as f:
f.write("Hello, Python!\n")
f.write("File handling is easy.")
# Append new data
with open("example.txt", "a") as f:
f.write("\nThis line is added at the end.")
5. Working with Binary Files
# Copy an image file
with open("image.jpg", "rb") as src:
with open("copy.jpg", "wb") as dest:
dest.write(src.read())
6. Best Practices
✅ Use with open()
to ensure files are automatically closed.
✅ Handle errors using try...except
.
✅ Always specify the correct encoding (encoding="utf-8"
) for text files.
7. Example: Word Counter Program
def count_words(filename):
try:
with open(filename, "r", encoding="utf-8") as f:
text = f.read()
words = text.split()
return len(words)
except FileNotFoundError:
return "File not found."
print(count_words("example.txt"))
8. Summary
- Use
open()
with modes (r
,w
,a
, etc.) to work with files. read()
,readline()
, and iteration allow you to process files.- Writing and appending data is simple with
"w"
and"a"
modes. - Always use
with open()
for safe and clean file handling. - Python supports text and binary file operations.