235

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()
martineau
  • 119,623
  • 25
  • 170
  • 301
Blackninja543
  • 3,639
  • 5
  • 23
  • 32

3 Answers3

394

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

f = open('/tmp/output', 'wb')
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 8
    Since OP seems to be using a non-Windows platform, this only works in Py3. In Py2, you would need to use `io.open`. – lvc Aug 23 '12 at 13:32
  • 3
    I think this is a bug in python itself, given python can detect data types at runtime, and can detect between binary and text input, I think it should be fixed in python itself, why are hundreds of people ending up in this page, if it could have been avoided by an if statement in the python stdlib, upvote if you agree, downvote me do oblivion if you must. – Felipe Valdes Jun 21 '18 at 21:23
  • 2
    @FelipeValdes unfortunately, that could introduce surprises when writing content if it were ever incorrectly detected. Even more annoyingly, that incorrect detection could only happen in certain strange edge cases that become surprising and difficult to track down. Relying on explicit behaviour instead, even if it means we have this question, ensures that I can have certainty in the way IO behaves under different scenarios. – Liam Dawson Jul 01 '18 at 03:22
  • 2
    what extension would the byte files have? – chia yongkang May 11 '20 at 08:48
  • @FelipeValdes it relates to the principle of least surprise/astonishment (https://en.wikipedia.org/wiki/Principle_of_least_astonishment). Your method would be more aptly named: `open_and_detect_file_type()` – henrycjc Jun 02 '20 at 04:35
  • how do I open `sys.stdout` in binary mode? – Jasen Apr 30 '21 at 00:33
  • https://stackoverflow.com/questions/908331/how-to-write-binary-data-to-stdout-in-python-3 – Jasen Apr 30 '21 at 00:35
29

Here is just a "cleaner" version with with :

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

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.

yaya
  • 7,675
  • 1
  • 39
  • 38
  • 1
    was able to create the file(new) without the `+` value in `wb+` as mentioned in ur answer. So just execute, ```python with open('data.csv', 'wb') as file_obj: file_obj.write(csv_data) ``` As per help(open) in REPL and python docs [Py3.7#reading&writingfiles](https://docs.python.org/3.7/tutorial/inputoutput.html#reading-and-writing-files) – Isaac Philip Sep 16 '20 at 06:56
  • @IsaacPhilip it works for me without + as well, so updated the answer. – yaya Sep 16 '20 at 12:15