Python File Handling
Learn the basics of working with files in Python - Start from zero!
📁 Welcome to File Handling!
File handling lets your Python programs save data, read information, and work with files on your computer. Think of it like teaching your program to read books and write notes!
# This is how easy it is to work with files!
with open('my_file.txt', 'w') as file:
file.write('Hello from Python!')
print("File created! 🎉")
What is File Handling?
File handling is like giving your Python program the ability to:
- 📖 Read information from files (like reading a book)
- ✍️ Write information to files (like writing in a notebook)
- ➕ Add new information to existing files
- 🗑️ Delete files when you don't need them
Understanding File Modes
Read Mode ('r')
Opens file for reading only
Write Mode ('w')
Creates new file or replaces existing
Append Mode ('a')
Adds content to end of existing file
Read-Write Mode ('r+')
Both read and write in same file
Your First File Operation
# Old way - you have to remember to close the file
file = open('example.txt', 'w')
file.write('Hello World!')
file.close() # Don't forget this!
print("File created the old way")
# Modern way - file closes automatically!
with open('example.txt', 'w') as file:
file.write('Hello World!')
# File is automatically closed here
print("File created the modern way!")
🌟 Why use 'with'?
- Automatically closes the file when done
- Works even if there's an error
- Cleaner and safer code
- This is how professionals do it!
Let's Try Different Modes
# Create a new file
with open('my_story.txt', 'w') as file:
file.write('Once upon a time...')
print("✅ Story file created!")
# Read the file we just created
try:
with open('my_story.txt', 'r') as file:
content = file.read()
print(f"Story content: {content}")
except FileNotFoundError:
print("❌ File not found!")
# Add more to our story
with open('my_story.txt', 'a') as file:
file.write(' And they lived happily ever after!')
print("✅ Story completed!")
# Read the complete story
with open('my_story.txt', 'r') as file:
complete_story = file.read()
print(f"Complete story: {complete_story}")
Detailed File Modes
Common file modes
- 'r' Read mode (default) - opens file for reading
- 'w' Write mode - creates new file or truncates existing
- 'a' Append mode - opens file for writing at end of file
- 'r+' Read-write mode - opens file for both reading and writing
- 'w+' Write-read mode - creates new file or truncates existing for reading and writing
- 'a+' Append-read mode - opens file for reading and writing at end of file
Binary modes (add 'b' to any mode)
- 'rb' Read binary mode
- 'wb' Write binary mode
- 'ab' Append binary mode
Text mode with encoding
open('file.txt', 'r', encoding='utf-8') # Specify encodingHandling Errors Like a Pro
# Safe way to open files
def safe_read_file(filename):
try:
with open(filename, 'r') as file:
content = file.read()
print(f"✅ Successfully read {filename}")
return content
except FileNotFoundError:
print(f"❌ File '{filename}' not found!")
except PermissionError:
print(f"❌ No permission to read '{filename}'!")
except Exception as error:
print(f"❌ Something went wrong: {error}")
return None
# Test it
safe_read_file('my_story.txt')
safe_read_file('missing_file.txt')
Getting File Information
import os
from datetime import datetime
# Create a test file
with open('info_test.txt', 'w') as file:
file.write('This file is for testing file information!')
# Get file information
filename = 'info_test.txt'
if os.path.exists(filename):
# File size
size = os.path.getsize(filename)
print(f"📏 File size: {size} bytes")
# Last modified time
mod_time = os.path.getmtime(filename)
readable_time = datetime.fromtimestamp(mod_time)
print(f"🕒 Last modified: {readable_time}")
# File path info
print(f"📁 Full path: {os.path.abspath(filename)}")
print(f"📄 Just filename: {os.path.basename(filename)}")
# Check permissions
print(f"👀 Can read: {os.access(filename, os.R_OK)}")
print(f"✏️ Can write: {os.access(filename, os.W_OK)}")
else:
print(f"❌ File '{filename}' doesn't exist!")
Working with Binary Files
# Working with binary files (like images, videos, etc.)
binary_data = b"This is binary data"
# Write binary file
with open('data.bin', 'wb') as file:
file.write(binary_data)
print("✅ Binary file created!")
# Read binary file
with open('data.bin', 'rb') as file:
read_data = file.read()
print(f"📊 Binary data: {read_data}")
print(f"📊 As text: {read_data.decode()}")
Modern File Handling with pathlib
from pathlib import Path
# Create a Path object
file_path = Path('modern_example.txt')
# Write to file
file_path.write_text('Hello from modern Python!')
# Read from file
content = file_path.read_text()
print(f"📄 Content: {content}")
# Check if file exists
if file_path.exists():
print(f"✅ File exists!")
print(f"📏 Size: {file_path.stat().st_size} bytes")
print(f"📁 Parent directory: {file_path.parent}")
print(f"🏷️ File name: {file_path.name}")
print(f"🔤 File extension: {file_path.suffix}")
Best Practices for Beginners
✅ Always Use 'with'
Use
with open()
instead of just
open()
🛡️ Handle Errors
Use try/except to handle file errors gracefully
🎯 Choose Right Mode
'r' for reading, 'w' for writing, 'a' for appending , 'b' for binary mode
🌍 Specify Encoding
Use
encoding='utf-8'
for text files
🎯 Practice Time!
# Simple file manager functions
import os
def create_file(filename, content):
"""Create a new file with content"""
try:
with open(filename, 'w') as file:
file.write(content)
print(f"✅ Created '{filename}'")
return True
except Exception as e:
print(f"❌ Error creating '{filename}': {e}")
return False
def read_file(filename):
"""Read and display file content"""
try:
with open(filename, 'r') as file:
content = file.read()
print(f"📄 Content of '{filename}':")
print(content)
return content
except FileNotFoundError:
print(f"❌ File '{filename}' not found!")
return None
def check_file(filename):
"""Check if file exists and show info"""
if os.path.exists(filename):
size = os.path.getsize(filename)
print(f"✅ '{filename}' exists - Size: {size} bytes")
return True
else:
print(f"❌ '{filename}' doesn't exist")
return False
# Test our file manager
create_file('test.txt', 'Hello, this is a test file!')
check_file('test.txt')
read_file('test.txt')