Skip to main content

How to Write Bytes to a File in Python with Path.write_bytes

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

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​

Syntax
from pathlib import Path

<count> = Path("<file>").write_bytes(<bytes>)
PartWhat 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​

write_bytes.py
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().

Step 2: Run It​

Terminal
uv run python write_bytes.py
Output
3
b'Hi!'

The terminal after uv run python write_bytes.py: 3, then 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​

MistakeWhat happensDo 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 existFileNotFoundError: [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​

SymptomLikely causeFix
a bytes-like object is required, not 'str'Text was passedPass bytes, or use write_text
FileNotFoundError when writingThe folder in the path doesn't existCreate 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​