Python gives you three main ways to write to a file, and which one you use depends on what you're writing and how much control you need

The simplest approach is the open() function with write mode. You open a file with open("filename.txt", "w"), use the write() method to add text, and close it with close(). The "w" mode creates a new file or overwrites an existing one. If you want to add to a file instead of replacing it, use "a" for append mode.

For most everyday tasks, though, you'll use a with statement. This automatically closes the file when you're done, even if something goes wrong. The pattern looks like this: with open("filename.txt", "w") as file: file.write("your text here"). This is safer because you don't have to remember to close the file yourself.

The third method is writelines(), which writes multiple lines at once. You pass it a list of strings, and it writes them all in one operation. This is faster when you have many lines to write because it makes fewer trips to the disk.

Key Takeaways

  • Use with open("filename.txt", "w") as file: for most file writing because it closes the file automatically and is safer than calling close() yourself.
  • The "w" mode creates a new file or replaces an existing one, while "a" mode adds to the end of a file without erasing what's already there.
  • Write single lines with file.write() or multiple lines at once with file.writelines(), depending on how your data is organized.
  • Always add newline characters (\n) yourself when using write() — Python doesn't add them automatically like some other languages do.

The with statement: The safest way to write files

The with statement is the standard approach in modern Python because it handles cleanup for you. When you write with open("data.txt", "w") as file:, Python opens the file, assigns it to the variable file, and guarantees it will close when the block ends — even if your code crashes partway through.

Here's a real example. If you're logging sensor readings to a file, you might write:

with open("sensor_log.txt", "w") as file:   file.write("Temperature: 72.5 degrees\n")   file.write("Humidity: 45%\n")

Notice the \n at the end of each line. Python's write() method doesn't add line breaks automatically — you have to include them. Without \n, both lines would appear on the same line in the file.

If you forget the with statement and use file = open("data.txt", "w") instead, you must call file.close() when you're done. If your program crashes before reaching that line, the file stays open and you might lose data. The with statement prevents this problem.

Write mode versus append mode: When to use each

The mode you choose when opening a file determines what happens to existing content. Write mode ("w") erases everything in the file and starts fresh. Append mode ("a") adds your new text to the end without touching what's already there.

Use write mode when you're creating a report or log that should start clean each time your program runs. For example, if you're generating a daily summary, you want "w" so yesterday's summary gets replaced. Use append mode when you're building a running record — like a log file that collects entries over days or weeks.

Here's the difference in practice. This code overwrites the file each time:

with open("report.txt", "w") as file:   file.write("Daily Report\n")   file.write("Processed 150 items\n")

This code adds to the file instead:

with open("log.txt", "a") as file:   file.write("2024-01-15: System started\n")   file.write("2024-01-15: Backup completed\n")

If you run the second example twice, the log file will contain four lines — both sets of entries. If you ran the first example twice, the report file would still contain only two lines because the second run replaced the first.

Writing multiple lines at once with writelines()

When you have many lines to write, writelines() is faster than calling write() over and over. It takes a list of strings and writes them all in a single operation, which means fewer disk accesses.

Here's how it works. If you have a list of names you want to save:

names = ["Alice\n", "Bob\n", "Charlie\n"] with open("names.txt", "w") as file:   file.writelines(names)

The file will contain three lines, one name per line. Notice that you still have to include \n in each string — writelines() doesn't add them for you either.

The performance difference matters most when you're writing thousands of lines. For small files, write() and writelines() are equally fast. But if you're processing a large dataset, building a list and using writelines() once is noticeably quicker than calling write() thousands of times.

Handling special characters and encoding

By default, Python writes files using UTF-8 encoding, which handles English, numbers, and most symbols without any extra work. But if you're writing text in other languages or using special characters, you should specify the encoding explicitly.

Add encoding="utf-8" to your open() call to be clear about what you're doing:

with open("message.txt", "w", encoding="utf-8") as file:   file.write("Café\n")   file.write("日本語\n")

This works on Windows, Mac, and Linux without surprises. If you don't specify encoding and your system uses a different default, the file might save incorrectly or your program might crash when it encounters a character it doesn't recognize.

For most projects, UTF-8 is the right choice. It's the standard on the web and in modern software. Only use a different encoding if you have a specific reason — like writing a file that an older Windows program expects in a particular format.

Common mistakes and how to avoid them

The most common mistake is forgetting the newline character. When you write multiple lines without \n, they all run together in the file. You'll open the file and see one long line instead of separate lines.

The second mistake is using write mode when you meant append mode. If you're building a log and accidentally use "w", you'll erase all previous entries the first time your program runs. Always think about whether you want to keep existing content or replace it.

The third mistake is not using a with statement. If you write file = open("data.txt", "w") and then forget to call file.close(), the file stays open in memory. Your program might not save the data you wrote, or other programs might not be able to read the file until your program exits.

A fourth issue is trying to write non-string data directly. If you have a number or a list, you can't pass it to write() — you have to convert it to a string first using str(). For example, file.write(str(42)) works, but file.write(42) raises an error.

Writing structured data: JSON and CSV

When you need to write data that other programs will read — like a spreadsheet or a web service — you usually don't write plain text. Instead, you use a format like JSON or CSV.

Python's json module handles JSON files. You create a dictionary or list, then use json.dump() to write it:

import json data = {"name": "Alice", "age": 30, "city": "Portland"} with open("person.json", "w") as file:   json.dump(data, file)

For CSV files (the format spreadsheets use), the csv module is simpler than writing commas yourself:

import csv rows = [["Name", "Age"], ["Alice", 30], ["Bob", 25]] with open("people.csv", "w") as file:   writer = csv.writer(file)   writer.writerows(rows)

These modules handle the details of formatting and escaping special characters, so you don't have to. If you write JSON or CSV by hand using write(), you'll almost certainly make mistakes that break the format.

Frequently Asked Questions

What's the difference between write() and writelines()?

write() takes a single string and writes it once. writelines() takes a list of strings and writes them all at once. Both require you to include newline characters yourself. Use writelines() when you have many lines to write at once, because it's faster than calling write() repeatedly.

Do I need to close the file if I use a with statement?

No. The with statement closes the file automatically when the block ends. That's the main reason to use it — you don't have to remember to call close() yourself, and the file closes even if your code crashes partway through.

What happens if the file doesn't exist when I try to write to it?

Python creates the file for you. Both "w" and "a" modes will create a new file if it doesn't exist. The "w" mode creates an empty file, and "a" mode also creates an empty file. Neither mode will raise an error if the file is missing.

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

No. If you try to write to "data/output.txt" and the "data" folder doesn't exist, Python will raise an error. You have to create the folder first using os.makedirs() or create it manually before running your program.

How do I write binary data instead of text?

Use "wb" mode instead of "w". Binary mode is for images, audio files, and other non-text data. You pass bytes to write() instead of strings. For most projects, text mode ("w" or "a") is what you need.