- write() — writing strings to files
- writelines() — writing multiple lines
- Appending — adding to existing files
- Different formats — CSV, JSON, and more
- Large files — efficient writing
- Error handling — robust file writing
Writing to Files in Python
Writing to files is essential for saving data, generating reports, and storing program output. Python provides several ways to write data to files, from simple strings to complex structured data.
Think of writing to a file like taking notes in a notebook. You can start a fresh page and fill it completely, or you can add new notes to the end of an existing page. Python gives you the flexibility to do both.
💡 Key concept: When writing to files, you need to decide whether to overwrite existing content or append to it. Python's 'w' mode overwrites, while 'a' mode appends. Choose based on your needs.
The write() Method
Writing Strings to Files
# The write() method writes a string to a file
# 1. Writing a simple string
with open("output.txt", "w") as file:
file.write("Hello, World!")
print(" File written with 'Hello, World!'")
# 2. Writing multiple strings
with open("multiple.txt", "w") as file:
file.write("First line\n")
file.write("Second line\n")
file.write("Third line\n")
print(" Multiple lines written")
# 3. Writing variables
name = "Alice"
age = 25
city = "NYC"
with open("user_data.txt", "w") as file:
file.write(f"Name: {name}\n")
file.write(f"Age: {age}\n")
file.write(f"City: {city}\n")
print(" User data written")
# 4. Writing from a list
fruits = ["Apple", "Banana", "Cherry", "Date"]
with open("fruits.txt", "w") as file:
for fruit in fruits:
file.write(f"{fruit}\n")
print(" Fruits list written")
# 5. Writing numbers
numbers = [10, 20, 30, 40, 50]
with open("numbers.txt", "w") as file:
for num in numbers:
file.write(f"{num}\n")
print(" Numbers written")
# 6. Writing with formatting
with open("formatted.txt", "w") as file:
file.write("=" * 40 + "\n")
file.write("REPORT\n")
file.write("=" * 40 + "\n")
file.write("Item | Price | Quantity\n")
file.write("-" * 40 + "\n")
file.write("Laptop | $999 | 2\n")
file.write("Phone | $599 | 3\n")
file.write("=" * 40 + "\n")
print(" Formatted report written")
write() method key points:
- Writes strings — only string data can be written
- No automatic newline — must add \n manually
- Returns count — number of characters written
- Overwrites by default — in 'w' mode
- Use f-strings — for formatting variables
Quick Check: What does write() return? (Answer: The number of characters written)
The writelines() Method
Writing Multiple Lines
# The writelines() method writes a list of strings
# 1. Writing a list of lines
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("writelines_example.txt", "w") as file:
file.writelines(lines)
print(" Multiple lines written with writelines()")
# 2. Writing without newlines (they'll all be on one line)
lines_no_newline = ["Apple", "Banana", "Cherry"]
with open("no_newline.txt", "w") as file:
file.writelines(lines_no_newline)
print(" Written without newlines (all on one line)")
# 3. Adding newlines when needed
items = ["Apple", "Banana", "Cherry"]
with open("items_with_newline.txt", "w") as file:
file.writelines(f"{item}\n" for item in items)
print(" Items with newlines")
# 4. Writing from a list comprehension
data = [1, 2, 3, 4, 5]
with open("comprehension.txt", "w") as file:
file.writelines(f"{num}\n" for num in data)
print(" Data written from comprehension")
writelines() key points:
- Writes list — takes a list of strings
- No automatic newlines — must include \n
- Efficient — writes multiple lines at once
- Can use generators — for memory efficiency
- Use with list comprehension — for transformations
Quick Check: What type of data does writelines() accept? (Answer: A list of strings)
Appending to Files
Adding to Existing Files
# Using 'a' mode to append to files
# 1. Basic appending
with open("append_test.txt", "a") as file:
file.write("This is appended content\n")
print("Content appended")
# 2. Creating a log file with timestamps
import datetime
def log_message(message):
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open("app.log", "a") as file:
file.write(f"[{timestamp}] {message}\n")
log_message("Application started")
log_message("User logged in: Alice")
log_message("Data processed: 100 records")
log_message("Application ended")
print("Log entries appended")
# 3. Appending to CSV
with open("data.csv", "a") as file:
file.write("Bob,30,LA\n")
file.write("Charlie,35,Chicago\n")
print(" CSV rows appended")
Appending key points:
- 'a' mode — opens file for appending
- Creates if missing — automatically creates new file
- Writes at end — always adds to the bottom
- Perfect for logs — tracking events over time
- No overwrite — preserves existing content
Quick Check: What mode should you use to add content to the end of a file? (Answer: 'a' mode)
Writing Different Formats
CSV, JSON, and More
# Writing different file formats
# 1. Writing CSV files
import csv
data = [
["Name", "Age", "City"],
["Alice", 25, "NYC"],
["Bob", 30, "LA"],
]
with open("people.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(data)
print(" CSV file created")
# 2. Writing JSON files
import json
json_data = {
"name": "Alice",
"age": 25,
"city": "NYC",
"hobbies": ["reading", "coding", "hiking"]
}
with open("data.json", "w") as file:
json.dump(json_data, file, indent=4)
print(" JSON file created")
Format writing key points:
- CSV — use csv module for proper formatting
- JSON — use json.dump() for structured data
- HTML — write as plain text
- Choose format — based on your use case
Quick Check: Which module is used to write JSON files? (Answer: json)
Writing Large Files
Efficient Writing for Big Data
# Writing large files efficiently
# 1. Using a generator for large data
def generate_data(count):
"""Generate data one item at a time"""
for i in range(count):
yield f"Data {i}\n"
# Write large file with generator
def write_generated_file(filename, total_lines=1000):
"""Write using a generator"""
with open(filename, "w") as file:
for line in generate_data(total_lines):
file.write(line)
print(f" Generated {total_lines} lines")
write_generated_file("large_data.txt", 1000)
# 2. Progress tracking for large writes
def write_with_progress(filename, total_lines=5000):
"""Write with progress tracking"""
with open(filename, "w") as file:
for i in range(total_lines):
file.write(f"Line {i}\n")
if i % 1000 == 0 and i > 0:
print(f"📊 Progress: {i}/{total_lines} lines")
print(" Write complete!")
Large file writing strategies:
- Generators — memory-efficient data generation
- Progress tracking — monitor long writes
- Chunk writing — write in batches
- Streaming — write continuously
Quick Check: What is the most memory-efficient way to write large files? (Answer: Using generators)
Error Handling When Writing
Robust File Writing
# Writing files can fail for many reasons
# Comprehensive write function
def safe_write_to_file(filename, content, mode="w"):
"""Safely write to a file with error handling"""
try:
with open(filename, mode) as file:
file.write(content)
print(f" Successfully wrote to '{filename}'")
return True
except PermissionError:
print(f" Permission denied for '{filename}'")
return False
except IsADirectoryError:
print(f" '{filename}' is a directory")
return False
except Exception as e:
print(f" Unexpected error: {e}")
return False
# Check directory before writing
import os
def write_to_directory(filename, content):
"""Write to a file, creating directories if needed"""
directory = os.path.dirname(filename)
if directory and not os.path.exists(directory):
try:
os.makedirs(directory, exist_ok=True)
print(f"📁 Created directory: '{directory}'")
except Exception as e:
print(f" Failed to create directory: {e}")
return False
return safe_write_to_file(filename, content)
Error handling key points:
- PermissionError — don't have write permission
- IsADirectoryError — trying to write to a directory
- Always check — directory existence before writing
- Handle gracefully — provide helpful error messages
Quick Check: What are common errors when writing files? (Answer: PermissionError and IsADirectoryError)
Best Practices for Writing Files
Professional File Writing Guidelines
# Best practices for writing files
# 1. Always use 'with' statement
# Good
with open("file.txt", "w") as f:
f.write("Content")
# Bad
f = open("file.txt", "w")
f.write("Content")
f.close() # Might be forgotten
# 2. Use the right mode
# Write new file or overwrite
with open("file.txt", "w") as f:
f.write("New content")
# Append to existing
with open("file.txt", "a") as f:
f.write("Added content")
# 3. Handle errors gracefully
try:
with open("file.txt", "w") as f:
f.write("Content")
except Exception as e:
print(f"Error: {e}")
# 4. Write data in the right format
# Convert non-string data to strings
data = {"key": "value"}
with open("data.txt", "w") as f:
f.write(str(data))
# Or use JSON for structured data
import json
with open("data.json", "w") as f:
json.dump(data, f)
# 5. Use constants for file paths
# DATA_DIR = "data"
# with open(os.path.join(DATA_DIR, "file.txt"), "w") as f:
Best practices summary:
- Use 'with' — automatic file closing
- Choose right mode — 'w' for write, 'a' for append
- Handle errors — use try-except blocks
- Format data — convert to strings or use JSON
- Use constants — avoid hardcoded paths
Quick Check: What is the most important best practice for file writing? (Answer: Always use the 'with' statement)
Try It Yourself
Experiment with writing to files in the editor below. Try different methods and see the results.
WRITE TO FILE PRACTICE
========================================
1. WRITE() - BASIC WRITING
File 'write_sample.txt' created
2. WRITELINES() - MULTIPLE LINES
File 'fruits.txt' created
3. APPENDING TO A FILE
File 'append_sample.txt' created with appended content
4. READING CREATED FILES
write_sample.txt content:
Hello, World!
This is line 2
This is line 3
fruits.txt content:
Apple
Banana
Cherry
Write to file practice complete!
You've Got It!
You now know multiple ways to write to files in Python. You understand write(), writelines(), appending, and how to handle different file formats.
Quick Quiz
Test what you've learned:
Frequently Asked Questions
What is the difference between write() and writelines()?
What is the difference between 'w' and 'a' modes?
How do I write numbers to a file?
str() or f-strings: file.write(str(42)) or file.write(f"{42}"). The write() method only accepts strings.
What's a common interview question about file writing?
Can I write to a file that doesn't exist?
How do I write a dictionary to a file?
json module: import json; json.dump(your_dict, file). This converts the dictionary to a JSON string that can be easily read back later. Or convert to string with str(your_dict).
Where to Go From Here
Now that you can write to files, check out these related topics:
Rename File
Learn how to rename files in Python.
Learn More →Copy File
Learn how to copy files in Python.
Learn More →Binary Files
Learn how to read and write binary files.
Learn More →