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!")
                                    
Easy
To Learn
3
Simple Steps
Safe
Method

File Writing Modes

πŸ“

Write Mode ('w')

Creates new file or overwrites existing

Fresh start Replaces old content
βž•

Append Mode ('a')

Adds content to end of existing file

Keeps old content Adds to end
πŸ”„

Write-Read Mode ('w+')

Write and read in same operation

Read & Write One operation
πŸ”’

Exclusive Mode ('x')

Creates file only if it doesn't exist

Safe creation No overwrite

Step 1: Your First File

Create 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 Several 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!")
Using writelines() Method

# 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

Add More Content

# 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 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

Save a Shopping List

# 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

Writing JSON 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']}")
Writing CSV Data

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

Write Binary Data

# 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

Safe File Creation with Exclusive Mode

# 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 Different Encodings

# 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-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

The Cool Modern Way

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

Safe File Writing

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

Create a Configuration File

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 Report

# 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!

Practice Exercise

# 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())

🧠 Quick Quiz

What does 'w' mode do when opening a file?

What does \n do in a string?

Which mode should you use to add content to an existing file?