简体   繁体   中英

Python writing hex to a file

I'm using Python 3 and I want to be able to write hex to a file like this but i cannot get it to work. This gives me a TypeError and if encode it the output to the file isn't correct.

junk = '\x90' * 5
junk += '\xcc' * 5

fo = open("foo.list", "wb")

fo.write(junk)
fo.close()

this gives me a type error, str doesn't support the buffer interface , if i however do this

junk = '01BDF23A'
junk += '90' * 5
junk += 'cc' * 5


fo = open("foo3.m3u", "wb")
fo.write(binascii.unhexlify(junk))
fo.close()

it works but i would like to define them as hex (\\x90), any ideas?

Thanks in advance for any help!

In Python 3, you must explicitly specify an encoding if you are trying to write a str . What you are trying to write are byte literals (see the python 2 to 3 guide ), so change the code to actually use byte literals

junk = b'\x90' * 5
junk += b'\xcc' * 5

fo.write(junk)

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