✍️ Writing Files
Writing files in Python is like giving your program the ability to save important information for later use. Whether you're creating a shopping list, saving game scores, or generating reports, file writing lets your program remember things between runs.
Think of file writing as your program's way to create digital notes - it can save data, create documents, and share information with other programs or users.
# 🎯 File Writing Demo
# Method 1: Create a simple text file
print("📝 Creating a simple file:")
with open("my_notes.txt", "w") as file:
file.write("Welcome to Python file writing!\n")
file.write("This is my first saved note.\n")
file.write("File writing is very useful!")
# Read it back to verify
with open("my_notes.txt", "r") as file:
content = file.read()
print("📄 File content:")
print(content)
# Method 2: Append more content
print("\n➕ Adding more content:")
with open("my_notes.txt", "a") as file:
file.write("\n\nThis line was added later.")
file.write("\nAppending keeps existing content safe!")
# Read the updated file
with open("my_notes.txt", "r") as file:
updated_content = file.read()
print("📄 Updated content:")
print(updated_content)
# Method 3: Writing different data types
print("\n💾 Saving user data:")
user_info = {"name": "Alice", "age": 25, "city": "New York"}
with open("user_info.txt", "w") as file:
file.write(f"User Information\n")
file.write(f"Name: {user_info['name']}\n")
file.write(f"Age: {user_info['age']}\n")
file.write(f"City: {user_info['city']}\n")
print("✅ User data saved successfully!")
🎯 Understanding File Writing Modes
Different file modes determine how Python handles existing content when writing files.
📄 Basic File Creation
Creating new files is the foundation of file writing - here's how to do it safely and effectively.
from datetime import datetime
# 📝 Simple File Creation Examples
def create_basic_files():
print("📄 Creating different types of files:")
# 1. Simple log file
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
log_entry = f"[{current_time}] Application started\n"
with open("app.log", "w") as file:
file.write(log_entry)
file.write("System initialization complete\n")
file.write("Ready to process requests\n")
print(" ✅ Log file created")
# 2. Configuration file
config_data = """# My App Settings
app_name = My Python App
version = 1.0
debug = false
max_users = 100
"""
with open("settings.conf", "w") as file:
file.write(config_data)
print(" ⚙️ Configuration file created")
# 3. User data file
users = [
{"name": "Alice", "email": "alice@example.com", "role": "admin"},
{"name": "Bob", "email": "bob@example.com", "role": "user"}
]
with open("users.txt", "w") as file:
file.write("User Database\n")
file.write("=" * 20 + "\n")
for user in users:
line = f"{user['name']} ({user['email']}) - {user['role']}\n"
file.write(line)
print(" 👥 User data file created")
# Verify files were created
import os
files = ["app.log", "settings.conf", "users.txt"]
print("\n📋 Verification:")
for filename in files:
if os.path.exists(filename):
size = os.path.getsize(filename)
print(f" ✅ {filename} ({size} bytes)")
create_basic_files()
🎨 Formatted Content Writing
Proper formatting makes your files readable and professional-looking for both humans and other programs.
# 📊 Formatted File Writing Examples
def create_formatted_files():
print("🎨 Creating formatted reports:")
# 1. Sales report with formatting
sales_data = [
("Product A", 150, 99.99),
("Product B", 75, 149.99),
("Product C", 200, 49.99)
]
with open("sales_report.txt", "w") as file:
file.write("SALES REPORT\n")
file.write("=" * 40 + "\n")
file.write(f"{'Product':<12} {'Qty':<5} {'Price':<8} {'Total':<10}\n")
file.write("-" * 40 + "\n")
total_revenue = 0
for product, qty, price in sales_data:
total = qty * price
total_revenue += total
file.write(f"{product:<12} {qty:<5} ${price:<7.2f} ${total:<9.2f}\n")
file.write("-" * 40 + "\n")
file.write(f"{'TOTAL REVENUE':<25} ${total_revenue:<9.2f}\n")
print(" 📈 Sales report created")
# 2. CSV format data
csv_data = [
["Name", "Age", "Department"],
["Alice", "28", "Engineering"],
["Bob", "32", "Marketing"],
["Carol", "26", "Design"]
]
with open("employees.csv", "w") as file:
for row in csv_data:
file.write(",".join(row) + "\n")
print(" 📋 CSV file created")
# 3. JSON-style data
import json
app_data = {
"app_name": "My Python App",
"version": "1.0",
"users": ["Alice", "Bob", "Carol"],
"settings": {
"theme": "dark",
"auto_save": True
}
}
with open("app_data.json", "w") as file:
json.dump(app_data, file, indent=2)
print(" 📦 JSON file created")
create_formatted_files()
➕ Appending to Files
Appending lets you add new content to existing files without losing what's already there.
# ➕ File Appending Examples
def demonstrate_appending():
print("➕ Demonstrating file appending:")
# Create initial log file
with open("activity.log", "w") as file:
file.write("Activity Log Started\n")
file.write("Initial setup complete\n")
print(" 📝 Created initial log file")
# Append new activities
activities = [
"User logged in",
"File uploaded",
"Data processed",
"Report generated"
]
for activity in activities:
with open("activity.log", "a") as file:
timestamp = datetime.now().strftime("%H:%M:%S")
file.write(f"[{timestamp}] {activity}\n")
print(" ➕ Added activities to log")
# Read and display the complete log
print("\n📖 Complete activity log:")
with open("activity.log", "r") as file:
for line_num, line in enumerate(file, 1):
print(f" {line_num}: {line.strip()}")
# Safe append with error handling
try:
with open("activity.log", "a") as file:
file.write(f"[{datetime.now().strftime('%H:%M:%S')}] Session ended\n")
print("\n✅ Session end logged successfully")
except Exception as e:
print(f"\n❌ Error appending to log: {e}")
demonstrate_appending()
🛡️ Safe File Writing
When writing important files, safety measures prevent data loss and ensure reliability.
🔒 Safe Writing Techniques
import os
import shutil
# 🛡️ Safe File Writing Examples
def safe_file_writing():
print("🔒 Demonstrating safe file writing:")
# Create important data
important_data = "Critical application data\nDo not lose this information!"
filename = "important.txt"
with open(filename, "w") as file:
file.write(important_data)
print(" 📄 Created important file")
# Safe update with backup
def safe_update_file(filename, new_content):
backup_name = filename + ".backup"
try:
# Step 1: Create backup if file exists
if os.path.exists(filename):
shutil.copy2(filename, backup_name)
print(f" 💾 Backup created: {backup_name}")
# Step 2: Write new content
with open(filename, "w") as file:
file.write(new_content)
print(f" ✅ File updated successfully")
return True
except Exception as e:
print(f" ❌ Update failed: {e}")
# Step 3: Restore from backup if needed
if os.path.exists(backup_name):
try:
shutil.copy2(backup_name, filename)
print(f" 🔄 File restored from backup")
except Exception:
print(f" ❌ Could not restore backup")
return False
# Test safe update
new_content = important_data + "\nUpdated with new information"
safe_update_file(filename, new_content)
# Verify the update
with open(filename, "r") as file:
content = file.read()
print(f"\n📖 Updated content:\n{content}")
safe_file_writing()
💾 Writing Different Data Types
Different types of data require specific formatting and handling when writing to files.
import json
from datetime import datetime
# 💾 Writing Various Data Types
def write_different_data_types():
print("💾 Writing different data types:")
# 1. Plain text
with open("notes.txt", "w") as file:
file.write("My Python Notes\n")
file.write("Learning file operations\n")
file.write("This is plain text content")
print(" 📝 Plain text written")
# 2. Numbers and calculations
numbers = [10, 25, 30, 45, 50]
with open("calculations.txt", "w") as file:
file.write("Number Analysis\n")
file.write("-" * 15 + "\n")
for num in numbers:
square = num ** 2
file.write(f"Number: {num:2d}, Square: {square:4d}\n")
total = sum(numbers)
average = total / len(numbers)
file.write(f"\nTotal: {total}, Average: {average:.1f}\n")
print(" 🔢 Numbers and calculations written")
# 3. Structured data as JSON
student_data = {
"name": "Alice Johnson",
"age": 22,
"courses": ["Python", "Math", "Science"],
"grades": {"Python": 95, "Math": 87, "Science": 92},
"enrolled": True,
"enrollment_date": "2024-01-15"
}
with open("student.json", "w") as file:
json.dump(student_data, file, indent=2)
print(" 📊 JSON data written")
# 4. Lists and dictionaries as text
inventory = {
"apples": 50,
"bananas": 30,
"oranges": 25
}
with open("inventory.txt", "w") as file:
file.write("Store Inventory\n")
file.write("=" * 20 + "\n")
for item, quantity in inventory.items():
file.write(f"{item.capitalize()}: {quantity} units\n")
total_items = sum(inventory.values())
file.write(f"\nTotal items: {total_items}\n")
print(" 📦 Inventory data written")
write_different_data_types()
📋 File Writing Reference
Quick reference for common file writing patterns and best practices.
Essential File Writing Methods
Understanding core file writing methods enables effective data saving and proper file creation in Python applications.
Method | Purpose | Example | Best Practice |
---|---|---|---|
file.write(text) | Write text to file | file.write("Hello") | Returns number of characters written |
file.writelines(list) | Write list of strings | file.writelines(lines) | Add newlines manually if needed |
file.flush() | Force write to disk | file.flush() | Ensure data is saved immediately |
file.writable() | Check if file is writable | can_write = file.writable() | Verify before writing |
file.seek(position) | Move to position in file | file.seek(0) | Position for overwriting |
file.tell() | Get current position | pos = file.tell() | Track write position |
file.truncate(size) | Resize file | file.truncate() | Remove content after position |
print(..., file=f) | Print to file | print("text", file=f) | Convenient for formatted output |
Writing files effectively gives your Python programs the ability to save information permanently. Whether you're creating configuration files, generating reports, or logging activities, these techniques will help you handle file writing safely and efficiently.
Test Your Knowledge
Test your understanding of file writing techniques:
What's Next?
Now that you understand how to write files effectively, you're ready to learn about file management. Discover how to organize files, check properties, and maintain your file system efficiently.
Ready to continue? Check out our lesson on File Management.
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.