How to write bytes to file?

Python

Python Problem Overview


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')
f.write(msg)
f.close()

Python Solutions


Solution 1 - Python

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

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

Solution 2 - Python

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.

Solution 3 - Python

Here is just a "cleaner" version with with :

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBlackninja543View Question on Stackoverflow
Solution 1 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 2 - PythonyayaView Answer on Stackoverflow
Solution 3 - PythonEtienne SalimbeniView Answer on Stackoverflow