How to Write Text to a File in Python with Path.write_text
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
from pathlib import Path
<count> = Path("<file>").write_text(<text>, encoding="utf-8")
| Part | What 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
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="")

Step 2: Run It
uv run python write_text.py
14
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
| Mistake | What happens | Do this instead |
|---|---|---|
| Calling it twice to add a line | The second call replaces the file: writing Oil the chain and then Fix the brakes left only Fix the brakes | Build the whole text first, or open the file with mode "a" to append |
| Expecting a line break at the end | write_text writes exactly what you give it: writing "A" and reading it back gave 'A', with no \n | Put \n at the end of the text yourself |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Only the last line is in the file | Each write_text call replaces the file | Write 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
- Path.write_text — the pathlib reference.
- Path.read_text — reading the text back.
