Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk2 min

How to Write a String to a File in Python

Write a string to a file in Python with open(), a context manager, and an explicit UTF-8 encoding. Choose overwrite or append mode based on whether existing contents should remain.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use open() in a with block, choose a mode, and call write(). For example, this writes a UTF-8 text file and replaces any existing contents:

text = "Hello, world!"

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

Choose whether to overwrite or append

The mode determines what happens to existing file contents. Python’s Python 3.12 tutorial on reading and writing files documents these common choices:

As an Amazon Associate I earn from qualifying purchases.

Mode What it does When to use it
"w" Opens for writing and erases existing contents in a file with the same name. Use when you intend to replace the file.
"a" Opens for appending; new data goes at the end. Use when you want to preserve existing contents and add more.
"r" Opens for reading. It is the default if you omit the mode. Not for writing.

Replace the file

text = "New contents"

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

Opening with "w" clears the old contents, so use it only when replacing them is intended.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Append to the file

with open("output.txt", "a", encoding="utf-8") as file:
    file.write("Another linen")

write() does not add a line break automatically. Include n in the string when you want the next text to start on a new line.

Why use a with block?

A with block closes the file when the block ends, including if an exception occurs. Python’s tutorial says it is good practice to use with for file objects and warns that without it—or an explicit close()—data passed to write() may not be fully written even if the program exits successfully. The examples here use the context manager so the file is closed reliably.

Set the text encoding explicitly

Text has to be encoded as bytes to be stored in a file. Python’s tutorial describes UTF-8 as the modern de facto standard and recommends specifying encoding="utf-8" unless another encoding is needed. If you omit the encoding, the default depends on the platform. In text mode, Python also translates newline characters to platform-specific line endings by default.

These examples are for text. For binary content such as images or executables, use binary mode rather than treating the data as a text string.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use pathlib for a concise one-call write

Path.write_text() writes the supplied string in text mode and closes the file for you. It overwrites an existing file, so it is suitable when replacement is intended:

from pathlib import Path

Path("output.txt").write_text("Hello, world!", encoding="utf-8")

The official pathlib reference says the encoding parameter has the same meaning as it does for open(). Use open() when you need to choose append mode or perform several operations through a file object; use write_text() for a direct text write that should replace the file.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Writing structured data as JSON

For a plain string, call file.write(text). If a list or dictionary should be stored in JSON format, serialize it with json.dump() instead. The Python 3.12 tutorial’s JSON section notes that JSON files must use UTF-8:

import json

value = {"message": "Hello, world!"}

with open("output.json", "w", encoding="utf-8") as file:
    json.dump(value, file)

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.