Python 3.5+pathlibfunction
.write_bytes()
reading/writing
Write bytes to the file, overwriting it entirely, and return the number of bytes written — the binary counterpart of `.write_text()`.
Syntax
p.write_bytes(data)
An existing file is truncated without any warning, and there is no append mode here — to add to the end use open(p, 'ab'). Missing parent directories are not created either: without them you get FileNotFoundError, so call p.parent.mkdir(parents=True, exist_ok=True) first.
Examples
from pathlib import Path
p = Path('test_pathlib.bin')
p.write_bytes(b'\xff\xfe') # → 2
p.read_bytes() # → b'\xff\xfe'
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy