Binary file operations often leverage Python’s buffer interface, which exposes an object’s raw memory buffer directly for compatible actions like raw byte writting. Objects like arrays also support direct binary reads into their internal buffers using readinto(). Here’s an example of standard text-to-binary and buffer-compatible writes, plus readinto usage:
with open('sample_binary_file.bin', 'rb') as binary_reader:
raw_bytes = binary_reader.read(20)
decoded_text = raw_bytes.decode('utf-8')
with open('sample_binary_file.bin', 'wb') as binary_writer:
source_text = 'Greetings, Pythonistas'
binary_writer.write(source_text.encode('utf-8'))
import array
integer_array = array.array('i', [5, 6, 7, 8])
with open('numeric_data.bin', 'wb') as array_writer:
array_writer.write(integer_array)
>>> import array
>>> target_buffer = array.array('i', [0]*10)
>>> with open('numeric_data.bin', 'rb') as array_reader:
... array_reader.readinto(target_buffer)
...
16
>>> target_buffer
array('i', [5, 6, 7, 8, 0, 0, 0, 0, 0, 0])
>>>
Buffer interface operations carry caveats: they are platform-dependent, relying on architecture-specific word lengths and byte orders (big-endian vs. little-endian).
Preventing Overwrites When Writing
To ensure data is only written to a new file and not an existing one, use Python 3’s exclusive write mode x (or xb for binary) instead of w. If the file already exists, FileExistsError is raised:
>>> with open('protected_document.txt', 'xt') as text_writer:
... text_writer.write('Confidential content')
...
19
>>> with open('protected_document.txt', 'xt') as text_writer:
... text_writer.write('Duplicate attempt')
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileExistsError: [Errno 17] File exists: 'protected_document.txt'
>>>
A less efficient alternative involves checking file existence first via os.path.exists, but x mode eliminates race conditions and simplifies code:
>>> import os
>>> if not os.path.exists('protected_document.txt'):
... with open('protected_document.txt', 'wt') as text_writer:
... text_writer.write('Alternate confidential content')
... else:
... print('File already exists; write aborted.')
...
File already exists; write aborted.
>>>
Note that x mode is a Python 3 extension and not available in older Python versions or standard C file I/O libraries.