The Python Oracle

How to write bytes to file?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Unforgiving Himalayas Looping

--

Chapters
00:00 How To Write Bytes To File?
00:24 Accepted Answer Score 401
00:34 Answer 2 Score 25
00:49 Answer 3 Score 32
00:57 Thank you

--

Full question
https://stackoverflow.com/questions/1209...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 401


If you want to write bytes then you should open the file in binary mode.

f = open('/tmp/output', 'wb')



ANSWER 2

Score 32


Here is just a "cleaner" version with with :

with open(filename, 'wb') as f: 
    f.write(filebytes)



ANSWER 3

Score 25


Write bytes and Create the file if not exists:

f = open('./put/your/path/here.png', 'wb')
f.write(data)
f.close()

wb means open the file in write binary mode.