How to write bytes to file?


I have a function that returns a string. The string contains carriage returns and newlines (0x0D, 0x0A). However when I write to a file it contains only the new line feeds. Is there a way to get the output to include the carriage return and the newline?

msg = function(arg1, arg2, arg3)
f = open('/tmp/output', 'w')
Asked By: Blackninja543



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

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

Write bytes and Create the file if not exists:

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

wb means open the file in write binary mode.

Answered By: yaya

Here is just a "cleaner" version with with :

with open(filename, 'wb') as f: 
Answered By: Etienne Salimbeni
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.