How to Write a String to a File in Python

To write a string to a file in Python, open the file in write mode and call write(): with open("file.txt", "w", encoding="utf-8") as f: f.write(text). Use mode "a" to append instead of overwriting, add \n for new lines, and convert numbers with str() first. This guide covers every way to write a string to a file in Python, including print(file=...) and pathlib, the file modes, newlines, encodings, bytes, and the errors you are most likely to hit.

All examples were run with Python 3.12.5 in the Windows Command Prompt; after each script, type shows what actually ended up in the file. Reference: open() and Reading and Writing Files in the Python docs.

Write a string to a file

text = "Hello from Python!"

with open("greeting.txt", "w", encoding="utf-8") as f:
    f.write(text)

print("Saved", len(text), "characters to greeting.txt")

Command Prompt output (the script, then type showing the file):

Saved 18 characters to greeting.txt
Hello from Python!
Command Prompt running a Python script that writes a string to greeting.txt with open and write, then type showing the file contents
The script writes the file; type greeting.txt shows its contents.
  • "w" creates the file, or empties it if it already exists.
  • The with block closes the file automatically, even if an error happens. (Without it, you must call f.close(), with parentheses.)
  • Always pass encoding="utf-8"; otherwise Python uses the system default, which on Windows may not handle every character.
  • write() returns the number of characters written.

Write a string with newlines

write() writes exactly what you give it; it never adds a line break. Add \n yourself, or use print(..., file=f), which ends the line for you:

with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("First line")                 # write() adds no newline
    f.write("Still the first line\n")    # add \n yourself
    f.write("Second line\n")
    print("Third line", file=f)           # print() adds the newline for you

with open("notes.txt", encoding="utf-8") as f:
    print(repr(f.read()))

Command Prompt output (the script, then type showing the file):

'First lineStill the first line\nSecond line\nThird line\n'
First lineStill the first line
Second line
Third line
Command Prompt output of Python writing lines to notes.txt with write and newline characters and print file argument, then type showing three lines
Two write() calls without \n end up on the same line.

Overwrite, append or create only: the file modes

The second argument of open() decides what happens to existing content:

from pathlib import Path

with open("log.txt", "w", encoding="utf-8") as f:     # "w": create or overwrite
    f.write("run 1\n")
with open("log.txt", "w", encoding="utf-8") as f:     # overwrite again: run 1 is gone
    f.write("run 2\n")
with open("log.txt", "a", encoding="utf-8") as f:     # "a": add to the end
    f.write("run 3 (appended)\n")

try:
    with open("log.txt", "x", encoding="utf-8") as f:  # "x": only create, never overwrite
        f.write("run 4\n")
except FileExistsError as e:
    print("FileExistsError:", e)

print(Path("log.txt").read_text(encoding="utf-8"))

Command Prompt output (the script, then type showing the file):

FileExistsError: [Errno 17] File exists: 'log.txt'
run 2
run 3 (appended)
run 2
run 3 (appended)
Command Prompt output showing Python file modes: w overwrites log.txt, a appends a line, x raises FileExistsError, then type shows the final file
"w" replaced run 1, "a" added run 3, and "x" refused to touch the existing file.
ModeIf the file existsIf it does not exist
"w"Empties it, then writesCreates it
"a"Writes at the endCreates it
"x"Raises FileExistsErrorCreates it
"r+"Reads and writes from the start (no truncation)Raises FileNotFoundError

Write a string with pathlib (one line)

Path.write_text() opens, writes and closes the file in one call. It always overwrites:

from pathlib import Path

report = Path("report.txt")
count = report.write_text("Total sales: 1,245\nTop region: Texas\n", encoding="utf-8")
print("characters written:", count)
print(report.read_text(encoding="utf-8"), end="")
print("size on disk:", report.stat().st_size, "bytes")

Command Prompt output (the script, then type showing the file):

characters written: 37
Total sales: 1,245
Top region: Texas
size on disk: 39 bytes
Total sales: 1,245
Top region: Texas

The text is 37 characters but 39 bytes on disk on Windows: each \n is saved as the two bytes \r\n (see the last section).

Write several strings or a list

Join the strings into one, or pass them to writelines(), which, despite its name, does not add line breaks either:

cities = ["Austin", "Denver", "Seattle"]

with open("cities.txt", "w", encoding="utf-8") as f:
    f.write("\n".join(cities) + "\n")                  # one string, joined

with open("cities2.txt", "w", encoding="utf-8") as f:
    f.writelines(city + "\n" for city in cities)       # writelines adds no newlines itself

with open("cities2.txt", encoding="utf-8") as f:
    print(f.read().splitlines())

Command Prompt output (the script, then type showing the file):

['Austin', 'Denver', 'Seattle']
Austin
Denver
Seattle

More options in write multiple lines to a file in Python and write a list to a file.

Write numbers and other values

write() only accepts strings. Convert other values with str() or format them with an f-string:

price = 19.99
qty = 3

with open("order.txt", "w", encoding="utf-8") as f:
    try:
        f.write(qty)                                     # write() only accepts str
    except TypeError as e:
        print("TypeError:", e)
    f.write(str(qty) + "\n")                             # convert with str()
    f.write(f"{qty} x ${price:.2f} = ${qty * price:.2f}\n")   # or use an f-string

Command Prompt output (the script, then type showing the file):

TypeError: write() argument must be str, not int
3
3 x $19.99 = $59.97
Command Prompt output of Python TypeError write() argument must be str, not int, then converting the number with str() and an f-string and type showing order.txt
TypeError: write() argument must be str, not int, and two ways to fix it.

To save variables of any type (and read them back), see write a variable to a file in Python.

Encoding: accents, symbols and emoji

Write non-English text with encoding="utf-8". A narrower encoding like ASCII fails on the first character it cannot represent:

text = "Café in São Paulo costs €4 ☕"

with open("utf8.txt", "w", encoding="utf-8") as f:
    f.write(text)

try:
    with open("ascii.txt", "w", encoding="ascii") as f:
        f.write(text)
except UnicodeEncodeError as e:
    print("UnicodeEncodeError:", e.reason, "for", repr(e.object[e.start:e.end]))

with open("utf8.txt", encoding="utf-8") as f:
    print(f.read())

Output:

UnicodeEncodeError: ordinal not in range(128) for 'é'
Café in São Paulo costs €4 ☕

Write bytes instead of text

Binary mode ("wb") takes bytes, not str. Convert a string with .encode():

data = "Price: 4 €".encode("utf-8")                   # str -> bytes (the € sign is 3 bytes in UTF-8)

with open("data.bin", "wb") as f:                        # "b": binary mode takes bytes
    count = f.write(data)
print("bytes written:", count)

with open("data.bin", "rb") as f:
    print(f.read())

try:
    with open("other.bin", "wb") as f:
        f.write("a normal string")
except TypeError as e:
    print("TypeError:", e)

Output:

bytes written: 12
b'Price: 4 \xe2\x82\xac'
TypeError: a bytes-like object is required, not 'str'

Line endings on Windows (newline argument)

In text mode on Windows, every \n you write is saved as \r\n. Pass newline="\n" to keep Unix line endings, for example for files used on Linux servers:

with open("windows.txt", "w", encoding="utf-8") as f:
    f.write("a\nb\n")
with open("unix.txt", "w", encoding="utf-8", newline="\n") as f:
    f.write("a\nb\n")

for name in ("windows.txt", "unix.txt"):
    with open(name, "rb") as f:
        print(name, f.read())

Output:

windows.txt b'a\r\nb\r\n'
unix.txt b'a\nb\n'

Related file-handling tutorials:

Frequently asked questions

How do I write a string to a file in Python?

with open("file.txt", "w", encoding="utf-8") as f: f.write(text). Or in one line: Path("file.txt").write_text(text, encoding="utf-8").

How do I append a string to a file instead of overwriting it?

Open the file with mode "a": open("file.txt", "a"). New text is added at the end.

Why is everything on one line in my file?

write() does not add line breaks. End each string with \n, or use print(text, file=f).

How do I fix TypeError: write() argument must be str, not int?

Convert the value first: f.write(str(number)) or f.write(f"{number}").

Do I need to close the file?

Not when you use with open(...); the file is closed automatically. Otherwise call f.close(), with parentheses.

How do I write a string to a file only if the file does not exist?

Use mode "x". It raises FileExistsError instead of overwriting an existing file.