0

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!

Emil Sit
  • 22,894
  • 7
  • 53
  • 75
John Wessen
  • 5
  • 1
  • 3
  • 2
    Post the error, please. – arshajii Jul 10 '13 at 17:01
  • The error is presumably [TypeError: 'str' does not support the buffer interface](http://stackoverflow.com/questions/5471158/typeerror-str-does-not-support-the-buffer-interface), assuming that you replace `b` with `junk`. – Emil Sit Jul 10 '13 at 17:10

1 Answers1

3

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)
Emil Sit
  • 22,894
  • 7
  • 53
  • 75