Open Binary File in Read and Write Mode with Python



To open binary files in binary read/write mode, specify 'w+b' as the mode(w=write, b=binary). For example,

f = open('my_file.mp3', 'w+b')
file_content = f.read()
f.write(b'Hello')
f.close()

Above code opens my_file.mp3 in binary read/write mode, stores the file content in file_content variable and rewrites the file to contain "Hello" in binary. You can also use r+mode as it doesn't truncate the file. 

Updated on: 2019-10-01T11:38:47+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements