How to Write Bytes to a File in Python with Path.write_bytes
When you have bytes in memory, such as a downloaded file or an image, Path.write_bytes saves them to a file in one line: it opens the file, writes the bytes and closes it again. This guide writes three bytes and reads them back, on Python 3.15.2.
Syntax
from pathlib import Path
<count> = Path("<file>").write_bytes(<bytes>)
| Part | What it means |
|---|---|
Path("<file>") | Where to save. The folder must already exist |
<bytes> | The data to write: bytes, not text |
<count> | The number of bytes written |
The pathlib reference says write_bytes will "Open the file pointed to in bytes mode, write data to it, and close the file".
The Example
Three byte values, 72, 105 and 33, are the codes for H, i and !. The script writes them to greeting.bin and 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
size = Path("greeting.bin").write_bytes(bytes([72, 105, 33]))
print(size)
print(Path("greeting.bin").read_bytes())
![The write_bytes.py script in a macOS-style code window: size = Path("greeting.bin").write_bytes(bytes([72, 105, 33])), then print(size) and print of read_bytes().](https://strdewiridedevblogsprod.blob.core.windows.net/images/blog/programming/python/2026/python-write-bytes-01-code.webp)
Step 2: Run It
uv run python write_bytes.py
3
b'Hi!'

write_bytes returned 3, the number of bytes written. read_bytes read them back, and Python shows the bytes for H, i and ! as b'Hi!'. The command works unchanged in PowerShell.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Writing text: write_bytes("Hi!") | TypeError: memoryview: a bytes-like object is required, not 'str' | Use write_text for text, or encode it: "Hi!".encode() |
| Writing into a folder that doesn't exist | FileNotFoundError: [Errno 2] No such file or directory: 'missing-folder/greeting.bin' | Create the folder first: Path("missing-folder").mkdir(parents=True, exist_ok=True) |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
a bytes-like object is required, not 'str' | Text was passed | Pass bytes, or use write_text |
FileNotFoundError when writing | The folder in the path doesn't exist | Create it with mkdir(parents=True, exist_ok=True) |
FAQ
Does write_bytes add to an existing file?
No, it replaces the file. Writing b"Hello" and then b"Hi" to the same file left b'Hi' in it.
How do I read the bytes back?
With Path("<file>").read_bytes(), as in the script.
Conclusion
Path("greeting.bin").write_bytes(bytes([72, 105, 33])) saved three bytes and returned 3, and read_bytes gave back b'Hi!'. It takes bytes only, replaces the file, and needs the folder to exist.
Additional Resources
- Path.write_bytes — the pathlib reference.
- Path.read_bytes — reading the bytes back.
