Death_Dealer
Death_Dealer

Reputation: 335

Appending hexlifyed content to file

file_1 = ('test.png')
with open(file_1, 'rb') as b:
    file_hex = b.read()    
binascii.hexlify(file_hex)
file_1_size = len(file_hex)
print (file_1_size)

file_new = open("test.tp", "a")
file_new.write(binascii.hexlify(file_hex))
file_new.close()

I've been trying to get this hexlifyed content appended to the file. I've even tried to apply the hexlifyed content to a variable of its own. like this,

file_1 = ('test.png')
with open(file_1, 'rb') as b:
    file_hex = b.read()    
x = binascii.hexlify(file_hex)
file_1_size = len(file_hex)
print (file_1_size)

file_new = open("test.tp", "a")
file_new.write(x)
file_new.close()

both end with error

TypeError: must be str, not bytes

Upvotes: 0

Views: 48

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121784

Open your file in binary mode to append bytes:

with open("test.tp", "ab") as file_new:
    file_new.write(x)

or decode your bytes to a string first:

with open("test.tp", "a") as file_new:
    file_new.write(x.decode('ascii')

Hex digits fall within the ASCII code range, so decoding with that codec is safe.

Upvotes: 1

Related Questions