Write Files in Python

Learn how to write text to files in Python using write() and writelines(), and understand the difference between write and append modes for saving data to disk.

5 min read

Writing data to a file is how your Python program leaves a mark on the world outside its own process. When you write a report, save user preferences, export processed data, or log what your program did during its run, you are using the same small set of methods on a file object opened in write mode. Python write files is a straightforward operation, but the details around truncation, newlines, and flushing determine whether your output file contains exactly what you intended or a jumbled mess of concatenated strings with no line breaks.

Before you can write to a file, you need to open it in a mode that permits writing. The most common choice is write mode, which creates the file if it does not exist and truncates it to zero length if it does. Truncation means the old content is gone the moment the open call succeeds, before your code has written a single byte. This behavior is intentional and useful when you want to generate a fresh output file, but it is also the source of a common and painful mistake: opening a file you meant to read with write mode destroys its contents instantly. Always double-check your mode string before running a script that opens existing files. If your goal is to add content to the end of a file without touching what is already there, you want append mode, which is covered in detail in the article on appending data to files in Python.

Writing strings with write()

The write method takes a single string argument and writes it to the file at the current position. It returns the number of characters written, though you rarely need to capture that return value in practice. What write does not do is add a newline after your string. If you call write with "Hello" and then write with "World", the file contains HelloWorld with no space and no line break between the two words. Every formatting decision is yours to make explicitly.

pythonpython
with open("greeting.txt", "w", encoding="utf-8") as file:
    file.write("Hello, Python.\n")
    file.write("This is line two.\n")
    file.write("And this is line three.\n")

Each call to write includes a trailing newline escape sequence at the end of the string. When you open the resulting file in a text editor, each sentence appears on its own line. If you omit those newlines, all three sentences run together on a single line, which is rarely what you want. The with statement ensures the file is closed after the block, and closing a file opened for writing flushes any data Python buffered in memory to the actual disk. Without the close, either explicit or through with, your data might sit in a buffer and never reach the file if the program crashes or exits unexpectedly.

The write method is strict about its input: it accepts only strings in text mode and only bytes objects in binary mode. If you pass a number, a list, or any other type, Python raises a TypeError. You must convert non-string data to strings before writing, using str for simple conversions or formatted strings for structured output. This strictness prevents silent data corruption by forcing you to decide how each piece of data should be represented as text.

Writing multiple lines with writelines()

The writelines method takes an iterable of strings and writes them to the file one after another. Despite its name, writelines does not add newlines between the strings; it writes exactly the content of each string in sequence, just as if you had called write for each one in a loop. The name refers to the fact that you typically pass it a list of strings where each string already represents a complete line, newline included.

pythonpython
lines = [
    "First line\n",
    "Second line\n",
    "Third line\n",
]
with open("output.txt", "w", encoding="utf-8") as file:
    file.writelines(lines)

This produces the same three-line file as three separate write calls with newlines. The advantage of writelines is that it expresses the intent of writing a pre-built list of lines in a single call, which can be more readable when the list is constructed elsewhere in your program. The disadvantage is that every string in the list must already be formatted correctly, newlines and all, because writelines will not fix formatting mistakes for you. For most situations, a for loop with write is equally clear and gives you the opportunity to format each line as you write it.

Write mode versus append mode

The distinction between write mode and append mode is one of the most important concepts in Python file handling, and confusing them leads to lost data. Write mode truncates the file to zero length when you open it, then writes your new content starting from the beginning. Append mode leaves the existing content untouched and positions the write pointer at the end of the file, so everything you write is added after whatever was already there.

Imagine opening a journal file with write mode on the second day. The first day's entry is erased before the second day's entry is written. Only the most recent entry survives. Opening with append mode instead preserves both entries, with each new one added after the last. This is the difference between a file that holds a complete history and one that only holds the latest snapshot. You will explore append mode thoroughly in the next article, but the core rule is simple: use write mode when you are creating a new file or intentionally replacing old content, and use append mode when you want to add to what is already there without losing anything.

Choosing encodings and writing binary data

When you open a file in text mode with an explicit encoding, Python converts every string you write into bytes using that encoding before the bytes reach the disk. The encoding you choose determines which characters can be written and how many bytes each character occupies. UTF-8 is the universal default for good reason: it can represent every Unicode character, is backward-compatible with ASCII for English text, and is understood by every modern text editor, browser, and data processing tool. Unless you have a specific reason to use another encoding, always pass encoding="utf-8" when opening text files for writing.

For binary data, open the file in binary write mode and write bytes objects instead of strings. You get bytes from network responses, image processing libraries, serialization modules, or by encoding a string yourself. Binary mode writes exactly the bytes you provide with no encoding or line-ending transformation, which is what you want when the output is not meant to be read as text.

Writing files is the complement to the reading skills you developed in the previous article on reading files in Python. Together, read and write form the core of data persistence in Python. Once you can read input from one file, process it in memory, and write the result to another file, you have the foundation for data pipelines, report generators, configuration managers, and every other kind of program that turns raw data into useful output.

Rune AI

Rune AI

Key Insights

  • Use open() with mode 'w' to write to a file; it creates the file if it does not exist and truncates it if it does.
  • The write() method writes exactly the string you give it; add
    explicitly for line breaks.
  • writelines() writes a list of strings at once, but each string must already contain its own newline.
  • Always close files you write to, or use the with statement, to ensure buffered data is flushed to disk.
  • For adding content without erasing existing data, use append mode 'a' covered in the next article.
RunePowered by Rune AI

Frequently Asked Questions

Does write() automatically add a newline at the end?

No. The write() method writes exactly the string you give it without adding anything extra. If you want each write to appear on its own line, you must include the newline character \n at the end of each string you pass to write(). Forgetting to add newlines is one of the most common mistakes when writing files in Python.

What happens if I open an existing file with write mode 'w'?

Opening a file in write mode 'w' immediately truncates it, meaning all existing content is erased before you even call write(). Use 'w' when you want to create a new file or completely replace the contents of an existing one. If you want to add content without erasing what is already there, use append mode 'a' instead.

When should I use writelines() instead of write()?

Use writelines() when you have a list of strings that each represent one line and you want to write them all to the file in one call. However, writelines() does not add newlines for you, so each string in the list must already end with \n if you want them on separate lines. For most cases, a for loop calling write() on each line is just as readable and gives you more control over formatting.

Conclusion

Writing files in Python is straightforward: open with 'w' for new or replacement content, call write() for each piece of text you want to save, include newlines explicitly, and close the file or use the with statement to flush data to disk. The same patterns scale from a two-line note to a generated report with thousands of rows. Pair writing with the reading skills from the previous article, and you can build programs that ingest data, transform it, and produce persistent output.