Python Write/Create Files
Learn to create and write files in Python - Easy for beginners!
βοΈ Let's Write Files!
Writing files in Python is super easy! You can save your data, create notes, or store information for later use. Let's start with the simplest example:
# Create a new file and write to it
with open('my_file.txt', 'w') as file:
file.write('Hello, World!')
print("File created successfully!")
File Writing Modes
Write Mode ('w')
Creates new file or overwrites existing
Append Mode ('a')
Adds content to end of existing file
Write-Read Mode ('w+')
Write and read in same operation
Exclusive Mode ('x')
Creates file only if it doesn't exist
Step 1: Your First File
# This creates a new file called 'hello.txt'
with open('hello.txt', 'w') as file:
file.write('Hello! This is my first file.')
print("β
File created!")
What does this code do?
-
open('hello.txt', 'w')- Creates a new file named 'hello.txt' -
'w'- Means "write mode" (creates new file or replaces existing) -
file.write()- Puts text into the file -
with- Automatically closes the file when done (very important!)
Step 2: Writing Multiple Lines
# Write multiple lines to a file
with open('my_notes.txt', 'w') as file:
file.write('My Daily Notes\n')
file.write('Today I learned Python!\n')
file.write('Writing files is fun!\n')
print("β
Notes saved!")
# Write multiple lines at once
lines = [
'Line 1: Introduction\n',
'Line 2: Main content\n',
'Line 3: Conclusion\n'
]
with open('multi_line.txt', 'w') as file:
file.writelines(lines)
print("β
Multiple lines written!")
π‘ Pro Tip
The
\n
creates a new line. Without it, all text would be on one line!
Step 3: Adding to Existing Files
# First, create a file
with open('diary.txt', 'w') as file:
file.write('Day 1: Started learning Python\n')
# Now add more content (use 'a' for append)
with open('diary.txt', 'a') as file:
file.write('Day 2: Learned about files\n')
file.write('Day 3: This is so cool!\n')
print("β
Diary updated!")
# Read it back to see the result
with open('diary.txt', 'r') as file:
print("Final diary content:")
print(file.read())
Step 4: Writing Numbers and Data
# Save different types of data
name = "Alice"
age = 25
score = 95.5
with open('student_data.txt', 'w') as file:
file.write(f'Student Name: {name}\n')
file.write(f'Age: {age}\n')
file.write(f'Test Score: {score}\n')
print("β
Student data saved!")
# Numbers must be converted to strings
with open('numbers.txt', 'w') as file:
file.write(str(42) + '\n')
file.write(str(3.14159) + '\n')
file.write(str(True) + '\n')
print("β
Numbers saved!")
π₯ Cool Feature: f-strings
The
f'{variable}'
syntax lets you put variables directly into text. Super handy!
Step 5: Writing Lists and Collections
# Create a shopping list
shopping_list = ['apples', 'bread', 'milk', 'eggs']
with open('shopping.txt', 'w') as file:
file.write('My Shopping List:\n')
for item in shopping_list:
file.write(f'- {item}\n')
print("β
Shopping list saved!")
# Save dictionary data
student_info = {
'name': 'Bob',
'age': 20,
'grade': 'A',
'subjects': ['Math', 'Science', 'English']
}
with open('student_info.txt', 'w') as file:
for key, value in student_info.items():
file.write(f'{key}: {value}\n')
print("β
Student info saved!")
Writing Structured Data
import json
# Create data structure
user_data = {
'name': 'Alice',
'age': 25,
'hobbies': ['reading', 'coding', 'gaming'],
'active': True
}
# Write JSON with pretty formatting
with open('user.json', 'w') as file:
json.dump(user_data, file, indent=2)
print("β
JSON data saved!")
# Read it back to verify
with open('user.json', 'r') as file:
loaded_data = json.load(file)
print(f"Loaded user: {loaded_data['name']}")
import csv
# Simple CSV data
csv_data = [
['Name', 'Age', 'City'],
['Alice', 25, 'New York'],
['Bob', 30, 'Los Angeles'],
['Charlie', 35, 'Chicago']
]
# Method 1: Manual CSV writing
with open('employees_simple.csv', 'w') as file:
for row in csv_data:
file.write(','.join(str(item) for item in row) + '\n')
print("β
Simple CSV created!")
# Method 2: Using csv module (better)
with open('employees_proper.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(csv_data)
print("β
Proper CSV created!")
Writing Binary Files
# Writing binary data (for images, videos, etc.)
binary_data = b"This is binary data \x00\x01\x02\x03"
with open('sample.bin', 'wb') as file:
file.write(binary_data)
print("β
Binary file created!")
# Read it back to verify
with open('sample.bin', 'rb') as file:
read_data = file.read()
print(f"Binary data: {read_data}")
print(f"As hex: {read_data.hex()}")
When to use binary mode:
- πΈ Images (JPG, PNG, GIF)
- π΅ Audio files (MP3, WAV)
- π¬ Video files (MP4, AVI)
- π¦ Any non-text file
Advanced Writing Techniques
# Exclusive mode - only creates if file doesn't exist
filename = 'exclusive_file.txt'
try:
with open(filename, 'x') as file:
file.write('This file was created safely!')
print(f"β
File '{filename}' created!")
except FileExistsError:
print(f"β File '{filename}' already exists!")
# Try again - should fail now
try:
with open(filename, 'x') as file:
file.write('This will not work!')
except FileExistsError:
print(f"β
Correctly prevented overwriting!")
# Writing with UTF-8 encoding (recommended for international text)
unicode_text = "Hello, δΈη! π CafΓ© naΓ―ve rΓ©sumΓ©"
with open('unicode_file.txt', 'w', encoding='utf-8') as file:
file.write(unicode_text)
print("β
Unicode file created!")
# Read it back to verify
with open('unicode_file.txt', 'r', encoding='utf-8') as file:
content = file.read()
print(f"Content: {content}")
# Write-read mode - write and read in same operation
with open('temp.txt', 'w+') as file:
file.write("Hello World!")
# Move to beginning to read
file.seek(0)
content = file.read()
print(f"Content in w+ mode: {content}")
# Append-read mode
with open('log.txt', 'a+') as file:
file.write("Log entry 1\n")
file.write("Log entry 2\n")
# Move to beginning to read all content
file.seek(0)
all_content = file.read()
print(f"All log content:\n{all_content}")
Modern Way: Using pathlib
from pathlib import Path
# Modern way with pathlib
file_path = Path('modern_file.txt')
# Write text the modern way
file_path.write_text('Hello from the future!')
# Write binary data
binary_path = Path('modern_binary.bin')
binary_path.write_bytes(b'Binary data')
# Check results
if file_path.exists():
print(f"β
File created: {file_path}")
print(f"π Size: {file_path.stat().st_size} bytes")
print(f"π Content: {file_path.read_text()}")
# Create directory and write file
output_dir = Path('output')
output_dir.mkdir(exist_ok=True)
output_file = output_dir / 'data.txt'
output_file.write_text('File in subdirectory')
print(f"β
File created in subdirectory: {output_file}")
Handle Errors Like a Pro
def safe_write_file(filename, content):
"""Write file with error handling"""
try:
with open(filename, 'w') as file:
file.write(content)
print(f"β
Successfully written: {filename}")
return True
except PermissionError:
print(f"β Permission denied: Cannot write to {filename}")
return False
except OSError as e:
print(f"β OS Error: {e}")
return False
except Exception as e:
print(f"β Unexpected error: {e}")
return False
# Test safe writing
safe_write_file('safe_test.txt', 'This is safe writing!')
# This might fail (protected location)
safe_write_file('/root/protected.txt', 'This will likely fail')
Why use try/except?
Sometimes things go wrong (disk full, no permission, etc.). This code handles errors gracefully instead of crashing your program!
π― Practical Examples
from datetime import datetime
def create_config_file():
"""Create a simple configuration file"""
config_content = f"""# My App Configuration
# Created on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
[settings]
theme = dark
language = english
auto_save = true
[database]
host = localhost
port = 5432
name = myapp
[features]
notifications = true
debug_mode = false
"""
with open('app_config.txt', 'w') as file:
file.write(config_content)
print("β
Configuration file created!")
create_config_file()
# Create a simple report
students = [
{'name': 'Alice', 'grade': 95},
{'name': 'Bob', 'grade': 87},
{'name': 'Charlie', 'grade': 92}
]
with open('grade_report.txt', 'w') as file:
file.write("STUDENT GRADE REPORT\n")
file.write("=" * 20 + "\n\n")
total = 0
for student in students:
file.write(f"{student['name']}: {student['grade']}%\n")
total += student['grade']
average = total / len(students)
file.write(f"\nClass Average: {average:.1f}%\n")
print("β
Grade report created!")
π Quick Reference
Create New File
open('file.txt', 'w')
Creates new or replaces existing
Add to File
open('file.txt', 'a')
Adds content to end
Write Text
file.write('text')
Puts text into file
New Line
'\n'
Creates line break
π― Try It Yourself!
# Create your own personal info file
name = input("What's your name? ")
age = input("How old are you? ")
hobby = input("What's your favorite hobby? ")
with open('about_me.txt', 'w') as file:
file.write(f'About Me\n')
file.write(f'========\n')
file.write(f'Name: {name}\n')
file.write(f'Age: {age}\n')
file.write(f'Hobby: {hobby}\n')
print("β
Your personal file has been created!")
# Read it back to see what we created
with open('about_me.txt', 'r') as file:
print("\nYour file contains:")
print(file.read())