Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Types of Exception
    • Exception Handling
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python: Write to File

Python Write to File - Complete Guide

Learn different ways to write data to files in Python — from simple text to complex formats.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
On this page:
  • Writing to Files in Python
  • The write() Method
  • The writelines() Method
  • Appending to Files
  • Writing Different Formats
  • Writing Large Files
  • Error Handling
  • Best Practices
  • Try It Yourself
  • Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You'll Learn Here
  • 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

1

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

2

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

3

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

4

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

5

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

6

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

7

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.

Loading Pyodide... 0%
Python Code Editor
========================================
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:

1. Which method writes a single string to a file?
2. What mode should you use to append to a file?
3. What does writelines() accept as input?
4. What is the most important best practice for file writing?
5. Which module is used to write JSON files?

Frequently Asked Questions

What is the difference between write() and writelines()? ▼

write() writes a single string to a file. writelines() writes a list of strings to a file. Both require you to add newline characters (\n) manually if you want each item on a separate line.

What is the difference between 'w' and 'a' modes? ▼

'w' mode overwrites the entire file (or creates it if it doesn't exist). 'a' mode appends to the end of the file (or creates it if it doesn't exist). Use 'w' when you want to replace content, 'a' when you want to add to it.

How do I write numbers to a file? ▼

You need to convert numbers to strings first using 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? ▼

Common questions include: "How do you write to a file in Python?" "What is the difference between 'w' and 'a' modes?" "How do you handle errors when writing files?" and "Explain the with statement for file handling."

Can I write to a file that doesn't exist? ▼

Yes! Both 'w' and 'a' modes will create the file automatically if it doesn't exist. Only 'x' mode (exclusive creation) will fail if the file already exists.

How do I write a dictionary to a file? ▼

The best way is to use the 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 →
Interview Resources
  • Python Syntax & Variables Interview Questions
  • Top SQL Interview Questions & Answers
  • SQL Joins: Displaying Data from Multiple Tables FAQ
Previous: Read Files Next: Rename File →