I have a small script here that I need some help with:
for song in songs:
slash = song.rindex('\\')
songbyte = slash + 2
if len(str(songbyte)) < 2:
#if songbyte < 10:
songbyte = "0" + str(songbyte)
f.write(binascii.a2b_hex(songbyte))
else:
f.write(binascii.a2b_hex("{0:x}".format(songbyte)))
f.close()
return
First off, I’m attempting to write a playlist. For testing purposes I’m writing one that contains 49 songs — songs is a list that i’m iterating through containing 49 songs
I’m required to write songbyte — It’s a value that ranges from 8 to 72. At the moment I’m just iterating through and making sure it has the correct value for each songbyte (It’s a copy of a known correct playlist, veryifying via diff and a hex editor).
My problem is that the line
print(binascii.a2b_hex("{0:x}".format(songbyte)))
throws “TypeError: Odd-length string”. Now, this is descriptive enough. Through investigating, I’ve determined that the value of songbyte when it’s going to error is 8. What doesn’t make sense, however, is that this error happens 37 songs into the list, and the majority of the the other songs’ songbytes are also 8 — and get caught with my len(str(songbyte)) < 2 check which adds a 0 — but strangely this one doesn’t.
Though I hope, I’m not really sure if this is enough information to help me solve the problem, short of providing complete details of the whole script though I don’t think I could. Is there another way that I can write songbyte — as hex — to a file?
You should use
struct.pack, which is meant exactly for this purpose:The format string
"{0:x}"will not insert zeroes before the number, you’d want"{0:02x}".Nevertheless, using binascii leads to unnecessarily complex and brittle code. For example, it would silently generate more than 2 characters if the value exceeds 255.