Python Write to File

Learn how to write to a file in Python using with open(). Create a new file, overwrite an existing file, append data, write multiple lines, and avoid common file mode mistakes.

Published

Updated

Read time 5 min read

Reviewed byDeepak Prasad

Python Write to File

To write data to a file in Python, open the path with open() or with open(), pick a write mode (w, a, or x), then call write() or writelines() on the file object. Mode w creates or overwrites a file; mode a appends without erasing what is already there; mode x creates an empty file only when the path does not exist yet.

This page covers create, overwrite, append, multiple lines, numbers, and file modes. For reading file contents, see read and write CSV in Python or the Python tutorial file section. Examples use tempfile.TemporaryDirectory() so nothing in your project folder is touched. File I/O snippets use {run=false}—copy them into a local python3 script to run.

Tested on: Python 3.13.3; kernel 6.14.0-37-generic.


Write to a file in Python

The usual pattern is with open(path, mode) as f: so Python closes the file when the block ends, even if an error occurs.

python
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "notes.txt"
    with open(path, "w") as f:
        f.write("Python write to file\n")
    print(path.read_text())

You should see one line printed: Python write to file.

Mode w opens the file for writing only. If the file exists, its contents are discarded before your data is written. If it does not exist, Python creates it. That makes w the right choice when you want a fresh file or a full replace—not when you need to keep old lines. If open() fails, handle OSError or FileNotFoundError with try / except rather than assuming every path is writable.

write() returns the number of characters written (Unicode code points in text mode). Text files accept strings only; convert numbers with str() or an f-string before writing (covered later).

You can still use open() without with, but you must call close() yourself:

python
f = open("notes.txt", "w")
f.write("hello\n")
f.close()

Prefer with open() in new code so a forgotten close() does not leave data buffered or locks held.


Append to a file in Python

Use mode a when you want to add lines at the end without deleting what is already on disk.

python
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "log.txt"
    with open(path, "w") as f:
        f.write("First line\n")
    with open(path, "a") as f:
        f.write("Second line\n")
    print(path.read_text())

You should see two lines: First line then Second line. If the file did not exist, a creates it—same as w, but without truncating when the file is already there.

Opening with w by mistake is a common bug: existing content is wiped immediately. When the file might already hold important data, use a or copy to a backup path first. To remove a file entirely, see Python delete file.


Create a new file in Python

There are three practical ways to create a file, depending on whether you want it empty, filled with content, or guaranteed not to clobber an existing path.

Empty file with x (create exclusive):

python
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "new.txt"
    with open(path, "x") as f:
        pass
    print(path.stat().st_size)

You should see 0—the file exists and is empty. Running open(path, "x") again on the same path raises FileExistsError.

Empty file with pathlib.Path.touch() (handy outside open()):

python
from pathlib import Path

Path("scratch.txt").touch()

Create and write in one step with w:

python
with open("report.txt", "w") as f:
    f.write("initial content\n")

Mode w creates the file if missing; if it already exists, content is replaced. Use x when overwrite would be a bug. To ensure parent folders exist before writing, see create nested directories.


Write multiple lines and different data types

write() does not add newlines. Pass \n in each string, or call write() once per line:

python
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "lines.txt"
    with open(path, "w") as f:
        f.write("First line\n")
        f.write("Second line\n")
    print(path.read_text())

For a list of strings, writelines() writes each item as-is (no extra newline between items unless each string includes \n):

python
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "lines.txt"
    with open(path, "w") as f:
        f.writelines(["First line\n", "Second line\n"])
    print(path.read_text())

Both snippets should print two lines.

Text mode files store strings. Numbers and other objects need conversion:

python
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "data.txt"
    count = 42
    ratio = 3.14
    with open(path, "w") as f:
        f.write(str(count) + "\n")
        f.write(f"ratio={ratio}\n")
    print(path.read_text())

You should see 42 on the first line and ratio=3.14 on the second. For structured tabular output, consider the csv module (covered in the read-write-csv guide linked in the introduction).


Python file modes

The second argument to open() is the mode. For writing, these are the ones you use most:

Mode Behavior
w Write only. Truncates existing file or creates a new one.
a Write only. Keeps existing content; new data goes at the end. Creates file if missing.
x Write only. Creates a new empty file; fails if the path already exists.
r+ Read and write on an existing file (does not truncate on open).
w+ Read and write; truncates or creates.
a+ Read and write; append writes, read can scan whole file.

Append b for binary mode (wb, ab, xb) when you write bytes—for example image or pickle payloads—not Unicode text. Text mode is the default (t is optional): open(path, "w") is the same as open(path, "wt").

Paths can be absolute or relative. Relative paths resolve from the process working directory (often the folder where you run python3 script.py). Use pathlib.Path or absolute paths when the location must be predictable. To check whether a path exists before choosing x vs w, see check if a file exists.


Summary

Write to a file in Python with with open(path, mode) as f: and f.write() or f.writelines(). Use w to create or overwrite, a to append without erasing existing lines, and x to create an empty file only when the name is free. Add \n yourself because write() does not insert line breaks, and convert numbers to strings before writing in text mode. Prefer with open() over manual close(), pick text vs binary mode deliberately, and link out to directory creation, existence checks, and delete helpers when your workflow needs them.


Frequently Asked Questions

1. What is the difference between w and a when writing a file in Python?

Mode w truncates the file to zero length and overwrites existing content (or creates the file); mode a keeps existing bytes and writes new data at the end.

2. Does file.write() add a newline in Python?

No—write() writes exactly the string you pass. Add \n yourself or use writelines() with newline characters in each line.

3. How do I create a new file without overwriting an existing one?

Use mode x with open(path, "x") to create an empty file and raise FileExistsError if the path already exists.

4. Should I use with open() or open() and close()?

Prefer with open() so the file closes even when an exception occurs; calling close() manually is easy to skip by mistake.
Deepak Prasad

R&D Engineer

Founder of GoLinuxCloud with more than 15 years of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive …