DarkGengar
DarkGengar

Reputation: 13

Python3: Writing data of bytes in a file

I want to write Bytes into a text file, but my problem is that I do not know how I can do this. I tried to write bytes with the write() function into a text file but I got the error:

TypeError: write() argument must be str, not bytes

Upvotes: 1

Views: 2969

Answers (3)

Paul Panzer
Paul Panzer

Reputation: 53109

If you are hellbent on writing bytes to a textfile you could use base64. Any reader of the file would have to be aware of that.

import base64

b'\xff\x00'.decode()
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

base64.b64encode(b'\xff\x00').decode()
# '/wA='
base64.b64decode('/wA='.encode())
# b'\xff\x00'

if you want numbers one way would be to use numpy:

import numpy as np

by = b'\x00\xffhello'
' '.join(len(by) * ['{:d}']).format(*np.frombuffer(by, np.uint8))
# '0 255 104 101 108 108 111'
' '.join(len(by) * ['{:02x}']).format(*np.frombuffer(by, np.uint8))
# '00 ff 68 65 6c 6c 6f'

relevant docs: numpy.frombuffer string formatting

Upvotes: 1

manvi77
manvi77

Reputation: 570

For reference: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

with open('some.txt', 'wb') as f:
    f.write(some_bytes)

Upvotes: -1

wim
wim

Reputation: 363556

You need to open the file in binary mode, instead of text mode:

import io

with io.open('/tmp/thefile.dat', 'wb') as f:
    f.write(some_bytes)

Upvotes: 2

Related Questions