Skip to main content

How to Write Text to a File in Python with Path.write_text

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

Path.write_text saves a string to a file in one line: it opens the file, writes the text and closes it again, with no with block. This guide writes a to-do line and reads it back, on Python 3.15.2.

Syntax​

Syntax
from pathlib import Path

<count> = Path("<file>").write_text(<text>, encoding="utf-8")
PartWhat it means
Path("<file>")Where to save. The folder must already exist
<text>The string to write, exactly as it is
encoding="utf-8"How the text is stored as bytes
<count>The number of characters written

The pathlib reference says write_text will "Open the file pointed to in text mode, write data to it, and close the file".

The Example​

The script writes one job, Oil the chain, to todo.txt, prints the number write_text returned, then reads the file back.

Prerequisites​

  • uv and Python 3. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with uv init.

Step 1: Write the Script​

write_text.py
from pathlib import Path

todo = Path("todo.txt")
written = todo.write_text("Oil the chain\n", encoding="utf-8")

print(written)
print(todo.read_text(encoding="utf-8"), end="")

The write_text.py script in a macOS-style code window: todo = Path("todo.txt"), written = todo.write_text("Oil the chain\n", encoding="utf-8"), then print(written) and print of read_text.

Step 2: Run It​

Terminal
uv run python write_text.py
Output
14
Oil the chain

The terminal after uv run python write_text.py: 14, then Oil the chain.

write_text returned 14: the 13 characters of Oil the chain plus the \n at the end. read_text read the line back. The command works unchanged in PowerShell.

Common Mistakes​

MistakeWhat happensDo this instead
Calling it twice to add a lineThe second call replaces the file: writing Oil the chain and then Fix the brakes left only Fix the brakesBuild the whole text first, or open the file with mode "a" to append
Expecting a line break at the endwrite_text writes exactly what you give it: writing "A" and reading it back gave 'A', with no \nPut \n at the end of the text yourself

Troubleshooting​

SymptomLikely causeFix
Only the last line is in the fileEach write_text call replaces the fileWrite everything in one call, or append with open("a")

FAQ​

What does write_text return?​

The number of characters written: 14 here.

How do I read the text back?​

With Path("<file>").read_text(encoding="utf-8"), as in the script.

Conclusion​

todo.write_text("Oil the chain\n", encoding="utf-8") saved the line and returned 14, and read_text gave it back. It replaces the file each time and adds nothing you didn't write.

Additional Resources​