✏️ Writing to Files
Python provides multiple ways to write to files. Understanding these methods is essential for data output, logging, and result storage.
# Basic file writing
with open('output.txt', 'w') as file:
file.write("Hello, Python!")
file.write("\nThis is a new line.")
🎯 Writing Methods
Python offers several approaches to write to files.
Basic Writing Methods
# Basic file writing
filename = 'output.txt'
# Write method
with open(filename, 'w') as file:
file.write("First line\n")
file.write("Second line\n")
# Writing multiple lines at once
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open(filename, 'w') as file:
file.writelines(lines)
print("Basic writing completed")
Writing with Print Function
# Using print function for file writing
filename = 'print_output.txt'
with open(filename, 'w') as file:
print("Hello from print!", file=file)
print("Another line", file=file)
print("Numbers:", 1, 2, 3, file=file)
print("Print-based writing completed")
Appending and Formatting
# Appending to existing file
filename = 'append_test.txt'
# First write some content
with open(filename, 'w') as file:
file.write("Initial content\n")
# Then append more content
with open(filename, 'a') as file:
file.write("Appended line\n")
# Writing with formatting
data = {'name': 'Alice', 'age': 25}
with open(filename, 'a') as file:
file.write(f"Name: {data['name']}\n")
file.write(f"Age: {data['age']}\n")
print("Appending and formatting completed")
🔍 Advanced Writing Techniques
Python allows more sophisticated file writing operations.
Error Handling
# Safe file writing with error handling
def safe_write_file(filename, content):
try:
with open(filename, 'w', encoding='utf-8') as file:
file.write(content)
print(f"Successfully wrote to {filename}")
return True
except PermissionError:
print(f"Permission denied: {filename}")
return False
except Exception as e:
print(f"Error writing file: {e}")
return False
# Test the function
result = safe_write_file('test.txt', "Test content")
print(f"Write operation successful: {result}")
Structured Data Writing
# Writing structured data as formatted text
students = [
{'name': 'Alice', 'grade': 'A'},
{'name': 'Bob', 'grade': 'B'},
{'name': 'Charlie', 'grade': 'C'}
]
with open('students.txt', 'w') as file:
file.write("Student Report\n")
file.write("=" * 20 + "\n")
for student in students:
file.write(f"{student['name']}: {student['grade']}\n")
print("Student report written successfully")
Backup and Logging
import os
import shutil
from datetime import datetime
# Backup existing file before writing
def write_with_backup(filename, content):
if os.path.exists(filename):
backup_name = f"{filename}.backup"
shutil.copy(filename, backup_name)
print(f"Created backup: {backup_name}")
with open(filename, 'w') as file:
file.write(content)
# Log writing function
def write_log(message, filename='app.log'):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
log_entry = f"[{timestamp}] {message}\n"
with open(filename, 'a') as file:
file.write(log_entry)
# Example usage
write_with_backup('important.txt', "New content")
write_log("Application started")
write_log("User logged in")
📋 File Writing Reference Table
Mode | Behavior | File Exists | File Missing |
---|---|---|---|
'w' | Write (overwrite) | Overwrites | Creates new |
'a' | Append | Appends to end | Creates new |
'x' | Exclusive create | Raises error | Creates new |
'w+' | Write + read | Overwrites | Creates new |
'a+' | Append + read | Appends | Creates new |
🎯 Key Takeaways
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.