📁 File Operations
File operations in Python let your programs save information, read existing data, and work with files on your computer. Think of it as giving your program the ability to remember things between runs - like saving your game progress or reading a shopping list from a text file.
Whether you're reading configuration files, saving user data, or processing documents, file operations are essential for building useful applications.
# 🎯 Quick Start: File Operations Demo
# Create and write to a file
with open("hello.txt", "w") as file:
file.write("Hello, Python Files!")
file.write("\nFile operations are awesome!")
# Read the file back
with open("hello.txt", "r") as file:
content = file.read()
print("📄 File content:")
print(content)
# Check if file exists
import os
print(f"✅ File exists: {os.path.exists('hello.txt')}")
# Simple file workflow
print("\n🔄 File Workflow Demo:")
data = ["Learn Python", "Practice coding", "Build projects"]
# Write list to file
with open("goals.txt", "w") as file:
for item in data:
file.write(f"• {item}\n")
# Read and display
with open("goals.txt", "r") as file:
print("📋 My Goals:")
print(file.read())
🎯 Understanding File Operations
File operations provide three main capabilities: reading existing files, writing new content, and managing files on your system.
📝 Text File Processing
Text files are perfect for human-readable data like configuration files, logs, and simple data storage.
# 📋 Configuration File Example
config_text = """# My App Settings
app_name = "My Python App"
version = "1.0"
debug = true
max_users = 50
"""
# Save configuration
with open("config.txt", "w") as file:
file.write(config_text)
# Read and parse configuration
print("⚙️ App Configuration:")
with open("config.txt", "r") as file:
for line in file:
line = line.strip()
if line and not line.startswith("#"):
print(f" {line}")
# User data example
users = ["Alice,Engineer,25", "Bob,Designer,30", "Carol,Manager,28"]
with open("users.txt", "w") as file:
file.write("Name,Job,Age\n") # Header
for user in users:
file.write(user + "\n")
print("\n👥 User Database:")
with open("users.txt", "r") as file:
header = file.readline().strip()
print(f"📊 {header}")
for line in file:
print(f" {line.strip()}")
💾 Data File Management
For structured data, JSON files provide an excellent way to save and load complex information.
import json
# 📊 Application data
app_data = {
"user_settings": {
"theme": "dark",
"language": "english",
"notifications": True
},
"recent_files": [
"project1.py",
"notes.txt",
"data.csv"
],
"statistics": {
"files_opened": 25,
"hours_used": 12.5
}
}
# Save data to JSON file
with open("app_data.json", "w") as file:
json.dump(app_data, file, indent=2)
print("💾 Application data saved!")
# Load and display data
with open("app_data.json", "r") as file:
loaded_data = json.load(file)
print("📱 Loaded Settings:")
print(f" Theme: {loaded_data['user_settings']['theme']}")
print(f" Files opened: {loaded_data['statistics']['files_opened']}")
print(f" Recent files: {len(loaded_data['recent_files'])}")
🔍 File Types and Formats
Different file types serve different purposes in your applications.
File operations form the foundation for data persistence in Python applications. Master these basics, and you'll be able to build programs that remember information and work with external data sources.
What You'll Learn
This section covers essential file operation skills that every Python developer needs:
- File Basics - Learn fundamental file concepts, opening and closing files safely
- Reading Files - Master techniques for reading content and processing text data
- Writing Files - Discover methods for creating files and saving data effectively
- File Management - Explore file system operations and implement backup strategies
Master these file operation concepts to build applications that can persist data, process external files, and manage information effectively!
What's Next?
Ready to start working with files? Begin with our lesson on File Basics to understand the fundamentals of file handling in Python.
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.