View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

How To Write to a File in Python

Updated on 20/05/20253,963 Views

Whether you're logging data, saving user input, or exporting results, writing to a file is a core skill in Python programming. The Python write file operation lets you store information outside your program so it can be reused, shared, or analyzed later. In this guide, we’ll dive deep into how to write to file in Python using built-in functions and best practices.

Also, if you’ve ever wondered:

  • How do I save text to a file using Python?
  • What’s the difference between write() and writelines()?
  • How do I append data instead of overwriting?

You're in the right place.

We'll walk through every essential detail, using simple language, clear examples, and plenty of code snippets. Each example will come with explanations and expected output to help you master the art of file writing in Python. Also, all this will help you in your journey to become an expert Python developer.

So, whether you're a beginner or brushing up your skills, this blog will cover everything you need to know about how to write to file in Python, from creating a file to writing plain text, appending data, and even working with binary files. Additionally, it’ll build the foundation for expert-level software development courses.  

A Brief Overview To Python write() file Method

When it comes to the Python write file process, one of the most commonly used methods is `write()`. This method is part of Python’s built-in file handling system, and it allows you to write string data directly to a file.

What is `write()` in Python?

The `write()` method is used when you want to write to file in Python—whether you're creating a new file or updating an existing one. The most important thing to remember is that `write()` only works with string data. If you want to write something else, like a list or integer, you’ll need to convert it first.

Also learn Global Variable in Python to develop advanced level programs. 

Here’s a simple example to help you understand how `write()` works.

Example: Using `write()` to Write to a File in Python

# Open a file named "example.txt" in write mode
with open("example.txt", "w") as file:
    # Writing a simple string to the file
    file.write("Hello, world! This is a Python write file example.")

Output:

This code does not display output in the terminal, but it creates a file named `example.txt` with the following content:

Hello, world! This is a Python write file example.

Explanation:

  • `open("example.txt", "w")` opens the file in write mode (`w`). If the file does not exist, it will be created. If it already exists, it will be overwritten.
  • `file.write()` writes the specified string into the file.
  • The `with` statement ensures the file is properly closed after writing, even if an error occurs.

This is the foundation of how to write to file in Python. Next, we’ll explore more ways to write data using `writelines()` and even structured data with `writerows()`.

Pilot your high-paying career with the following full-stack development courses: 

Writing to a File in Python (`write()`, `writelines()`, `writerows()`)

Once you're comfortable with the `write()` method, it's time to expand your file-handling toolkit. Python offers several methods for writing data to files, each tailored to specific use cases. In this section, we’ll explore three commonly used approaches to write to file in Python: `write()`, `writelines()`, and `writerows()` from the `csv` module.

Each of these methods plays a distinct role in the broader Python write file workflow.

1. Using Python `write()` file method – Writing Single Strings

You’ve already seen how `write()` can be used to store a single string in a file. Here's another quick example to reinforce the idea:

# Open the file in write mode
with open("single_line.txt", "w") as file:
    # Write a single line of text
    file.write("This is a single line written to the file.")

Output:

Contents of `single_line.txt`:

This is a single line written to the file.

Explanation:

Use `write()` when you need to write a single string or line at a time. This is the most direct way to write to file in Python.

Also, learn about List Methods in Python for in-depth understanding of the Python programming. 

2. Using `writelines()` – Writing Multiple Lines at Once

When you have a list of strings and want to write them to a file in one go, `writelines()` is your friend. It writes a sequence of strings without adding newlines automatically, so you’ll need to include `\n` manually if needed.

# Prepare a list of lines to write
lines = [
    "First line of text\n",
    "Second line of text\n",
    "Third line of text\n"
]

# Write multiple lines using writelines()
with open("multiple_lines.txt", "w") as file:
    file.writelines(lines)

Output:

Contents of `multiple_lines.txt`:

First line of text

Second line of text

Third line of text

Explanation:

  • `writelines()` takes an iterable (like a list or tuple) and writes each string to the file.
  • Make sure each line includes a newline character (`\n`), or all lines will run together.

`writelines()` is ideal for bulk writing when you're working with a list of string content. It's a practical way to write to file in Python efficiently.

By learning all these different concepts, you can leverage all the advantages of Python programming

3. Using `writerows()` – Writing Rows to a CSV File

If you're working with structured data like tables, the `csv` module’s `writerows()` function is perfect. It allows you to write to file in Python in a tabular format, commonly used in spreadsheets and data exchange.

import csv

# Define rows of data
data = [
    ["Name", "Age", "City"],
    ["Alice", "30", "New York"],
    ["Bob", "25", "Los Angeles"],
    ["Charlie", "35", "Chicago"]
]

# Open a CSV file for writing
with open("people.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerows(data)

Output:

Contents of `people.csv`:

Name,Age,City

Alice,30,New York

Bob,25,Los Angeles

Charlie,35,Chicago

Explanation:

  • `csv.writer()` prepares the file for structured writing.
  • `writerows()` writes a list of lists as rows in the CSV file.
  • Use `newline=""` in `open()` to prevent blank lines in some systems.

When you're working with structured data, `writerows()` is a clean and powerful way to write to file in Python.

Each of these methods—`write()`, `writelines()`, and `writerows()`—helps you handle file writing with precision and flexibility. As you get more comfortable, you’ll find yourself choosing the right one based on your data and use case.

Do explore String formatting in Python to develop high-end applications. 

Creating and Writing to a New File

A common need in many Python applications is to generate new files and store output, logs, or user-generated content. Thankfully, Python makes this straightforward with the built-in `open()` function and the appropriate file modes. In this section, we’ll walk through how to write to file in Python when you want to create a file from scratch or ensure it’s written afresh.

Writing with `"w"` Mode – Create or Overwrite a File

When using `"w"` mode, Python will create a file if it doesn’t exist or completely overwrite it if it does. This is the simplest way to write to file in Python when the contents need to be reset.

# Create or overwrite a file
with open("new_file.txt", "w") as file:
    file.write("Creating a brand new file.\n")
    file.write("This demonstrates the Python write file process.\n")

Output:

`new_file.txt` will be created (or overwritten) with:

Creating a brand new file.

This demonstrates the Python write file process.

Use Case: When you're sure you want to discard any previous content.

Writing with `"x"` Mode – Create File Only if It Doesn’t Exist

To ensure an existing file isn’t overwritten by accident, `"x"` mode helps you safely create a new file. It raises an error if the file already exists.

# Attempt exclusive creation
try:
    with open("protected_file.txt", "x") as file:
        file.write("This file is created only if it doesn't exist.\n")
except FileExistsError:
    print("File already exists. Creation skipped.")

Output: 

If a file doesn’t exist, it’ll be created, otherwise a message will be displayed. 

Use Case: When protecting existing data is critical and overwriting is not allowed.

Learn about Regular Expressions in Python to easily understand every code implementation. 

Writing to an Existing File in Python

If the file already exists and contains valuable data, you likely want to modify it rather than overwrite it. Python supports this need with `"a"` and `"r+"` modes, both essential tools in the Python write file toolkit.

Appending with `"a"` Mode – Add Content to the End

Use `"a"` mode when you want to write to file in Python without affecting the existing content. This is perfect for log files or progressive data collection.

# Append new content to an existing file
with open("log.txt", "a") as file:
    file.write("New log entry added.\n")

Output:

New content is added after the existing file content. No overwriting occurs.

Use Case: Useful for audit logs, incremental saves, or running history.

To ease your Python development, learn about different Python Frameworks and Memory Management in Python

Updating with `"r+"` Mode – Read and Modify Existing Files

For more advanced file edits, `"r+"` mode lets you read and write to an existing file. However, writing starts at the beginning and can overwrite content unless you manage the file pointer carefully.

# Read and write (with overwrite starting at beginning)
with open("status.txt", "r+") as file:
    file.write("Status: Updated\n")

Output: 

The content in the files gets updated. 

Caution:

If the new content is shorter than the original, leftover text may remain.

Use Case: When you need both read and write access, such as updating headers or modifying fixed-length lines.

Additionally, to ensure all Python programs run smoothly, learn how to correctly install Python on Windows

Writing to a Binary File in Python

Text files are the most common format when working with Python, but not all data is text. Sometimes you need to write to file in Python in a way that preserves the exact byte representation—such as when working with images, audio files, executable data, or serialized objects. That’s where binary file writing comes in.

Binary files handle raw byte data. Unlike text mode, which interprets characters based on encodings like UTF-8, binary mode writes data exactly as it exists in memory. This makes it essential when you're working with non-textual or encoded content. 

Also explore Speech Recognition in Python to develop next-gen applications. 

Writing Binary Data with `"wb"` Mode

To write to a binary file in Python, open the file in `"wb"` mode (write binary). This mode creates the file if it doesn't exist and overwrites it if it does.

# Define binary data (for example, image bytes or any raw byte stream)
binary_data = b'\x42\x69\x6e\x61\x72\x79\x20\x66\x69\x6c\x65\x20\x65\x78\x61\x6d\x70\x6c\x65'

# Write binary data to a file
with open("binary_output.bin", "wb") as file:
    file.write(binary_data)

Output: 

A file named `binary_output.bin` is created and filled with the exact bytes from `binary_data`. This file isn’t human-readable but can be read by programs expecting that byte structure.

Explanation:

  • `b'...'` defines a bytes object, which is required when writing to a file in binary mode.
  • `"wb"` tells Python to open the file for binary writing.
  • `file.write()` functions the same way as in text mode, but accepts only `bytes` objects.

Writing Binary Data from Strings or Objects

Sometimes you’ll want to write binary data derived from strings or other structures. You can encode strings to bytes or serialize complex data using modules like `pickle`.

Example: Encoding a String and Writing It

# Convert a string to bytes and write it
text = "Binary mode Python write file example"
encoded_text = text.encode("utf-8")

with open("encoded_text.bin", "wb") as file:
    file.write(encoded_text)

Result:

`encoded_text.bin` will contain a binary representation of the string, useful for compatibility with byte-based systems or APIs.

Example: Using `pickle` to Write Serialized Objects

import pickle

# Some Python data to serialize
data = {"username": "admin", "access": True, "id": 42}

# Write the serialized object as binary
with open("user_data.pkl", "wb") as file:
    pickle.dump(data, file)

Output: 

  • No visible output in the console, as the code doesn't print anything.
  • A new file named user_data.pkl will be created in the current working directory. This file contains the binary representation of the data dictionary.

Explanation:

  • `pickle.dump()` serializes Python objects into binary format.
  • The file `user_data.pkl` can later be reopened with `pickle.load()` to restore the object.

Key Notes When Writing Binary Files

  • Always use binary mode (`"wb"` or `"ab"`) when handling non-text data.
  • Only `bytes` objects (or data encoded as bytes) can be written in binary mode.
  • Useful for writing images, compressed data, byte streams, or serialized objects.
  • For appending, use `"ab"` instead of `"wb"`.

Binary mode is a powerful extension of the Python write file capabilities and is essential for low-level data manipulation and storage beyond plain text.

Conclusion 

Mastering how to write to file in Python is fundamental for working with data, automating tasks, and building practical applications. From creating new files with write() to handling multiple lines with writelines() or structured data using writerows(), Python offers flexible and powerful tools for writing to files. We also explored how to safely create or modify files using various modes like "w", "a", "x", and "r+", giving you complete control over how your data is stored and preserved.

Beyond plain text, we covered how to write to a file in Python using binary mode—an essential skill for working with byte-level data such as images, encoded strings, and serialized objects. Choosing the right method and mode ensures data integrity, reduces errors, and improves the reliability of your scripts. With these techniques, you’re well-prepared to handle any file writing requirement Python throws your way.

FAQs 

1. What is the write() method in Python?

The `write()` method in Python is used to write a string or sequence of characters to a file. When the file is opened in write mode (`"w"`), the `write()` method writes the data to the file. If the file already exists, it will be overwritten. If the file doesn’t exist, Python will create it. Keep in mind that `write()` doesn't automatically add a newline character, so it has to be explicitly included if needed.

2. How can I create a new file in Python?

To create a new file in Python, you can use the `open()` function with modes like `"w"` (write) or `"x"` (exclusive creation). When using `"w"`, the file is created if it doesn’t already exist, but if it does, it will be overwritten. Using `"x"` mode ensures that a new file is created only if it doesn't exist already; otherwise, it raises a `FileExistsError`. Always handle these situations carefully to prevent unintentional data loss.

3. Can I write multiple lines to a file in Python?

Yes, you can write multiple lines to a file using the `writelines()` method. It takes a list or iterable of strings and writes each one to the file sequentially. However, `writelines()` does not automatically insert line breaks between the lines, so you need to include `\n` (newline) characters within each string if you want separate lines. This method is often faster for writing large numbers of lines compared to writing them one by one with `write()`.

4. How do I append data to an existing file?

To append data to an existing file, you can open the file in append mode (`"a"`). In this mode, Python will add new content to the end of the file without modifying the existing data. If the file doesn’t exist, it will be created. The `"a"` mode is ideal for situations where you don’t want to overwrite any existing content, such as when adding log entries or adding incremental data.

5. What is the difference between write() and writelines()?

The `write()` method writes a single string to the file, while `writelines()` writes a sequence of strings, typically from a list or iterable. The main difference is that `write()` writes one string at a time, and it does not automatically add newlines (`\n`) between strings, which means you must include them if needed. On the other hand, `writelines()` can write multiple lines in one call, but it also doesn’t add newline characters, so you need to handle them manually.

6. How do I read from a file in Python?

Reading from a file in Python can be done using the `open()` function with modes like `"r"` (read), `"r+"` (read/write), or others. After opening the file, you can use methods like `read()` to get the entire content, `readline()` to read one line at a time, or `readlines()` to get a list of all lines in the file. Always close the file after reading to free system resources, or use the `with` statement to ensure the file is automatically closed after the operation.

7. What is the "w" mode in Python?

The `"w"` mode in Python is used when you want to open a file for writing. If the file doesn’t already exist, Python creates it. However, if the file already exists, opening it in `"w"` mode will overwrite its contents. This mode is ideal for creating or replacing files but be cautious because it will erase any pre-existing data. For scenarios where you don’t want to overwrite an existing file, other modes like `"a"` or `"x"` should be considered.

8. How can I write binary data to a file?

To write binary data in Python, you should open the file in binary write mode (`"wb"`). Binary data is represented as `bytes` objects, which are collections of raw bytes. When writing binary data, Python will write the exact byte sequence to the file without interpreting it as text. This mode is commonly used for files like images, videos, or other non-text data formats. Ensure you're dealing with binary-compatible data before using this method to avoid errors.

9. What happens if I try to write to a read-only file?

If you attempt to write to a read-only file in Python, you will encounter a `PermissionError`. This error happens because the file's permissions do not allow writing. To resolve this issue, you must change the file permissions or choose a different file that has write permissions. You can also use a try-except block to catch the exception and handle the error gracefully, allowing the program to continue without crashing.

10. How do I handle errors when writing to files?

To handle errors when writing to files in Python, use a `try-except` block around the file operations. Common errors include `FileNotFoundError` if the file doesn’t exist or `PermissionError` if the file is read-only. You can catch these exceptions and take action, such as notifying the user, retrying the operation, or creating the file if it doesn’t exist. Using error handling ensures your program doesn’t crash unexpectedly and can respond to unexpected situations.

11. Can I write to a file without overwriting its content?

Yes, you can write to a file without overwriting its existing content by opening the file in append mode (`"a"`). This mode adds new data to the end of the file, leaving the current content intact. It’s a great option when logging information or adding new data incrementally. If the file doesn’t exist, it will be created. Just remember, while this mode is safe for appending data, it doesn't give you control over where in the file the data is written. 

image

Take our Free Quiz on Python

Answer quick questions and assess your Python knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.