Yusuf2020
Yusuf2020

Reputation: 23

Error "TypeError: a bytes-like object is required, not 'int'"

oldfile = open("buscrash_diversion.uexp", "rb")
l = list(oldfile.read())
out = open("1", "wb")
for i in l:
    out.write(i)

If i execute this

TypeError: a bytes-like object is required, not 'int'

If i execute this

import struct
oldfile = open("buscrash_diversion.uexp", "rb")
l = list(oldfile.read())
out = open("1", "wb")
for i in l:
    out.write(struct.pack("b", i))
struct.error: byte format requires -128 <= number <= 127

I can't solve this problem for a week, even if i use "bytearray" it gives the following error

TypeError: can assign only bytes, buffers, or iterables of ints in range(0, 256)

Where am i doing wrong ?

Upvotes: 2

Views: 7553

Answers (2)

InQβ
InQβ

Reputation: 521

Integer list is not bytes-like, but you can simply cast it into bytes.

oldfile = open("oldfile", 'rb')
l = list(oldfile.read())
out = open("newfile", 'wb')
for i in l:
    out.write(bytes([i]))

Although the above should solve your problem, FYI, you should use struct.pack('B', ...) for unsigned byte (which is [0..255]), 'b' for signed byte (which is [-128..127]).

Upvotes: 2

Sumant Guha
Sumant Guha

Reputation: 111

You open and write to the files in binary mode (the b flag in open/write). Remove this flag to be able to write non-byte data

oldfile = open("buscrash_diversion.uexp", "r")
l = list(oldfile.read())
out = open("1", "w")
for i in l:
    out.write(i)

Upvotes: 1

Related Questions