The three ways to write to a file in Python

Python gives you three main ways to write to a file: open() with write mode, open() with append mode, and pathlib.Path. The first two are the standard approach and work in every Python version. The third is newer and cleaner if you are already using pathlib elsewhere in your code.

The most common method uses open() with the mode parameter set to 'w' (write) or 'a' (append). Write mode creates a new file or overwrites an existing one. Append mode adds content to the end of an existing file without erasing what is already there. Both require you to close the file when you are done, or use a with statement to close it automatically.

The pathlib approach uses Path.write_text() or Path.write_bytes() and handles file closing for you. It is shorter for simple operations but less flexible for large files or repeated writes.

Key Takeaways

  • Use open(file, 'w') to create a new file or overwrite an existing one, and open(file, 'a') to add content to the end without erasing what is there.
  • Always use a with statement when opening files so Python closes them automatically, even if an error occurs.
  • Call .write() to add a single string, or .writelines() to add multiple strings from a list without adding line breaks between them.
  • Use pathlib.Path.write_text() for simple one-time writes when you do not need to open and close the file manually.
  • Remember that write mode ('w') erases the file first, while append mode ('a') preserves existing content.

Writing a single string with open() and write mode

The simplest approach is to open a file in write mode, write your content, and let the with statement close it automatically. Here is the actual code:

with open('output.txt', 'w') as file:   file.write('Hello, World!')

This creates a file named output.txt in your current working directory and writes the string to it. If output.txt already exists, this code erases it first. The with statement ensures the file closes automatically when the block ends, even if an error occurs inside it.

If you need to write multiple lines, add the newline character \n to each line:

with open('output.txt', 'w') as file:   file.write('Line 1\n')   file.write('Line 2\n')   file.write('Line 3\n')

Adding content without erasing with append mode

Append mode ('a') opens an existing file and adds content to the end without erasing what is already there. If the file does not exist, it creates one:

with open('output.txt', 'a') as file:   file.write('New line added\n')

This is useful when you are logging data, collecting results from multiple operations, or building a file over time. Each call to write() adds to the end of the file.

The difference between write and append matters. Write mode starts fresh every time. Append mode preserves everything that came before. If you open a file in write mode twice in the same program, the second open erases what the first one wrote.

Writing multiple lines at once with writelines()

The .writelines() method takes a list of strings and writes them all at once. Unlike its name suggests, it does not add line breaks between items — you have to include \n in each string yourself:

lines = ['First line\n', 'Second line\n', 'Third line\n'] with open('output.txt', 'w') as file:   file.writelines(lines)

This is faster than calling .write() three separate times, especially with large lists. However, if your list does not include newline characters, all the text runs together on one line in the file.

A common pattern is to build a list of strings in your program, then write them all to a file in one operation. This is cleaner than opening and closing the file multiple times.

Using pathlib for simpler one-time writes

The pathlib module offers a shorter syntax for writing to a file when you do not need to open it manually:

from pathlib import Path Path('output.txt').write_text('Hello, World!')

This creates the file and writes the string in one line. The file closes automatically. If the file exists, it is overwritten. Use Path.write_bytes() instead if you are writing binary data like images or encoded files.

The pathlib approach is cleaner for simple tasks but less flexible for repeated writes or large files. If you need to write to the same file multiple times in your program, using open() with a with statement is more efficient because you open the file once instead of multiple times.

Handling file paths and directories

When you write to a file, Python looks for it in your current working directory unless you provide a full path. You can find your current directory by running import os; print(os.getcwd()). To write to a different folder, include the path in the filename:

with open('/home/user/documents/output.txt', 'w') as file:   file.write('Content here')

On Windows, use backslashes or raw strings: r'C:\Users\user\documents\output.txt' or 'C:/Users/user/documents/output.txt'. Python accepts forward slashes on Windows too, which is often simpler.

If the directory does not exist, Python raises a FileNotFoundError. Create the directory first using os.makedirs() or Path.mkdir() before writing to a file inside it.

Choosing between text and binary mode

The examples above use text mode (the default). Python treats the content as a string and handles line endings automatically. Binary mode ('wb' for write, 'ab' for append) writes raw bytes and is used for images, audio files, or other non-text data:

with open('output.bin', 'wb') as file:   file.write(b'Binary data here')

Notice the b prefix on the string — this tells Python it is bytes, not text. Binary mode does not interpret or convert line endings, so what you write is exactly what ends up in the file. Use text mode for anything human-readable, and binary mode for everything else.

Frequently Asked Questions

What happens if I write to a file that does not exist?

Python creates the file automatically in write mode ('w') or append mode ('a'). The file appears in your current working directory unless you specify a different path. If the directory does not exist, Python raises an error.

How do I add content to a file without erasing what is already there?

Use append mode ('a') instead of write mode ('w'). Open the file with open(file, 'a') and call .write() or .writelines(). Append mode preserves all existing content and adds your new content at the end.

Do I have to close the file manually?

No, if you use a with statement. Python closes the file automatically when the block ends. If you call open() without with, you must call .close() yourself, or the file stays open in memory until your program ends.

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

.write() takes a single string. .writelines() takes a list of strings and writes them all at once. Neither adds line breaks automatically — you must include \n in your strings if you want separate lines in the file.

Can I write to a file in a folder that does not exist yet?

No, Python raises a FileNotFoundError. Create the directory first using os.makedirs(directory_path) or Path(directory_path).mkdir(parents=True) before writing to a file inside it.