File Handling in Python: Your Digital Filing Cabinet đ
Imagine you have a magical filing cabinet in your room. This cabinet can hold letters, pictures, homework, and secrets. But to use it, you need to know how to:
- Open the drawer (open the file)
- Read whatâs inside (read from files)
- Put new things in (write to files)
- Close the drawer properly (close the file)
Python gives you this exact magical cabinet for your computer!
The Big Picture
graph TD A["Your Python Code"] --> B["Open File"] B --> C{Choose Mode} C --> D["Read 'r'"] C --> E["Write 'w'"] C --> F["Append 'a'"] D --> G["Get Content"] E --> H["Create/Replace"] F --> I["Add to End"] G --> J["Close File"] H --> J I --> J
Opening Files: Unlocking the Cabinet
Before reading or writing, you must open the file. Think of it like unlocking a drawer with a key.
The Magic Spell
file = open("diary.txt", "r")
Whatâs happening?
"diary.txt"â The name of your file"r"â The mode (read mode)fileâ Your handle to work with it
Real Example
# Open a file called "story.txt"
my_file = open("story.txt", "r")
print("File opened!")
my_file.close() # Always close!
Why close? Imagine leaving your cabinet drawer open forever. Bad things happen! Files can get corrupted. Always close what you open.
File Modes: Choosing Your Superpower
When you open a file, you pick a mode. Each mode gives you different powers:
| Mode | Meaning | What It Does |
|---|---|---|
"r" |
Read | Look at content (file must exist) |
"w" |
Write | Create new or erase old, then write |
"a" |
Append | Add to the end (keeps old content) |
"r+" |
Read+Write | Both read and write |
"rb" |
Read Binary | For images, videos, etc. |
"wb" |
Write Binary | Create binary files |
The Key Difference
# WRITE mode - Erases everything first!
file = open("notes.txt", "w")
file.write("New content only")
file.close()
# APPEND mode - Adds to the end!
file = open("notes.txt", "a")
file.write("\nMore content added")
file.close()
Remember: "w" is like getting a blank page. "a" is like adding to your list.
Reading from Files: Peeking Inside
There are THREE ways to read. Pick the one that fits!
Method 1: Read Everything
file = open("poem.txt", "r")
content = file.read()
print(content)
file.close()
This grabs ALL the text at once. Great for small files!
Method 2: Read Line by Line
file = open("shopping.txt", "r")
first_line = file.readline()
second_line = file.readline()
print(first_line)
print(second_line)
file.close()
Each readline() grabs ONE line. Like reading one item from your shopping list.
Method 3: Get All Lines as a List
file = open("names.txt", "r")
all_lines = file.readlines()
print(all_lines)
# Output: ['Alice\n', 'Bob\n', 'Charlie\n']
file.close()
Now you have a list! Each line is one item.
Loop Through Lines (Best Practice)
file = open("tasks.txt", "r")
for line in file:
print(line.strip())
file.close()
.strip() removes the \n (newline character) at the end.
Writing to Files: Leaving Your Mark
Writing puts YOUR words into a file. Itâs like writing in your diary.
Write a Single Line
file = open("message.txt", "w")
file.write("Hello, World!")
file.close()
Important: write() doesnât add newlines automatically!
Write Multiple Lines
file = open("list.txt", "w")
file.write("Apples\n")
file.write("Bananas\n")
file.write("Cherries\n")
file.close()
Or use writelines():
fruits = ["Apples\n", "Bananas\n", "Cherries\n"]
file = open("list.txt", "w")
file.writelines(fruits)
file.close()
The with Statement: Your Safety Net
Hereâs the best way to work with files. Itâs like having a robot that ALWAYS closes the file for you!
The Old Way (Risky)
file = open("data.txt", "r")
content = file.read()
# What if error happens here?
file.close() # Might never run!
The Smart Way (Safe)
with open("data.txt", "r") as file:
content = file.read()
print(content)
# File closes automatically here!
Magic! When the with block ends, Python closes the file. Even if an error happens!
Why with is Amazing
graph TD A["with open..."] --> B["File Opens"] B --> C["Your Code Runs"] C --> D{Error?} D -->|Yes| E["File Still Closes!"] D -->|No| F["File Closes"] E --> G["Safe!"] F --> G
Pro tip: Always use with for file handling. Itâs the Pythonic way!
File Position Methods: Where Am I?
When you read a file, Python uses a cursor (like your finger pointing at words while reading).
Key Methods
| Method | What It Does |
|---|---|
tell() |
Shows current cursor position |
seek(n) |
Moves cursor to position n |
See It in Action
with open("sample.txt", "r") as file:
print(file.read(5)) # Read first 5 chars
print(file.tell()) # Position: 5
file.seek(0) # Go back to start
print(file.tell()) # Position: 0
print(file.read()) # Read everything
The Cursor Journey
Imagine your file contains: HELLO
Position: 0 1 2 3 4 5
Content: H E L L O [end]
^
Cursor starts here
After read(3):
Position: 0 1 2 3 4 5
Content: H E L L O [end]
^
Now here!
Binary vs Text Files: Two Worlds
Files come in two flavors:
Text Files
- Human-readable
- Contains letters, numbers, symbols
- Examples:
.txt,.csv,.json,.py
with open("story.txt", "r") as file:
text = file.read()
print(text) # Readable!
Binary Files
- Computer-readable
- Contains raw bytes (0s and 1s)
- Examples:
.jpg,.mp3,.pdf,.exe
with open("photo.jpg", "rb") as file:
data = file.read()
print(data[:20]) # Shows bytes
# Output: b'\xff\xd8\xff\xe0\x00\x10JFIF...'
Copying a Binary File
# Copy an image
with open("original.jpg", "rb") as source:
data = source.read()
with open("copy.jpg", "wb") as dest:
dest.write(data)
print("Image copied!")
Quick Comparison
| Feature | Text Mode | Binary Mode |
|---|---|---|
| Mode | "r", "w", "a" |
"rb", "wb", "ab" |
| Returns | String | Bytes |
| Use For | Documents | Images, Audio |
| Newlines | Converted | Raw |
Putting It All Together
Hereâs a complete example that shows everything working:
# Create a to-do list app
# 1. Write tasks to file
with open("todos.txt", "w") as file:
file.write("Buy groceries\n")
file.write("Do homework\n")
file.write("Call mom\n")
# 2. Read and display tasks
print("Your Tasks:")
with open("todos.txt", "r") as file:
for i, line in enumerate(file, 1):
print(f"{i}. {line.strip()}")
# 3. Add a new task
with open("todos.txt", "a") as file:
file.write("Learn Python\n")
# 4. Show updated list
print("\nUpdated Tasks:")
with open("todos.txt", "r") as file:
print(file.read())
Output:
Your Tasks:
1. Buy groceries
2. Do homework
3. Call mom
Updated Tasks:
Buy groceries
Do homework
Call mom
Learn Python
Common Mistakes to Avoid
1. Forgetting to close files
# BAD
file = open("data.txt")
data = file.read()
# Forgot to close!
# GOOD
with open("data.txt") as file:
data = file.read()
# Auto-closes!
2. Wrong mode for operation
# BAD - Can't write in read mode
file = open("data.txt", "r")
file.write("Hello") # Error!
# GOOD
file = open("data.txt", "w")
file.write("Hello") # Works!
3. File not found
# Handle missing files gracefully
try:
with open("missing.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("Oops! File doesn't exist.")
Key Takeaways
- Always open before using - Use
open() - Choose the right mode -
r,w,a, or binary versions - Use
withstatement - It closes files automatically - Text vs Binary - Know which type youâre working with
tell()andseek()- Navigate within files
You now have the keys to Pythonâs filing cabinet! Practice these concepts, and youâll be a file-handling master in no time.
