Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write bytes to file?

Tags:

python

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()
like image 549
Blackninja543 Avatar asked Aug 23 '12 13:08

Blackninja543


People also ask

How do you create a byte file?

Convert byte[] array to File using Java In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it in a file. Example: Java.

What is bytes format?

A byte is a group of 8 bits. A bit is the most basic unit and can be either 1 or 0. A byte is not just 8 values between 0 and 1, but 256 (28) different combinations (rather permutations) ranging from 00000000 via e.g. 01010101 to 11111111 . Thus, one byte can represent a decimal number between 0(00) and 255.


3 Answers

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

f = open('/tmp/output', 'wb')
like image 103
Ignacio Vazquez-Abrams Avatar answered Sep 25 '22 19:09

Ignacio Vazquez-Abrams


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.

like image 23
yaya Avatar answered Sep 24 '22 19:09

yaya


Here is just a "cleaner" version with with :

with open(filename, 'wb') as f: 
    f.write(filebytes)
like image 12
Etienne Salimbeni Avatar answered Sep 25 '22 19:09

Etienne Salimbeni