简体   繁体   中英

TypeError: a bytes-like object is required, not 'str', for writing string to file

            for d in range(0,d2.size):
                c2 += str(d2.item(d))
            cf.write(chr(int(c2,2)))

Getting error in cf.write(chr(int(c1,2)))

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

Code was running fine on python 2.x

In your comment you said that you were opening the file as a bytes by using the argument wb however you're trying to write a string to the file which causes the error.

To fix that all you have to do is convert the string to bytes

for d in range(0,d2.size):
    c2 += str(d2.item(d))
    cf.write(bytes(chr(int(c2,2)), 'utf-8'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM