Blackninja543
Blackninja543

Reputation: 3709

How to prevent that CR and LF are changed when writing 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')
f.write(msg)
f.close()

Upvotes: 240

Views: 374391

Answers (3)

Etienne Salimbeni
Etienne Salimbeni

Reputation: 582

Here is just a "cleaner" version with with :

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

Upvotes: 32

yaya
yaya

Reputation: 8273

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.

Upvotes: 25

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799300

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

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

Upvotes: 403

Related Questions