Hi, Right now I'm trying to write a list of hex values (strings) to a disk file in Python 3.1. Code: ['AB', 'EC', 'CD', 'AB', 'ED', 'EB', 'DB', 'AB', 'EC'] I tried adding \x before each one and then writing it to file, but it's writing it literally as '\xAB\xEC\xCD\xAB\xED\xEB\xDB\xAB\xEC'. What do I need to do to write it as bytes? Thanks.
['AB', 'EC', 'CD', 'AB', 'ED', 'EB', 'DB', 'AB', 'EC']
http://linux.byexamples.com/archives...g-binary-file/
Last edited by Vaphell; December 7th, 2010 at 05:48 AM.
You might want to post more of your code to illustrate exactly what you've tried.
Originally Posted by Vaphell http://linux.byexamples.com/archives...g-binary-file/ I tried that an it spat out: Code: TypeError: must be bytes or buffer, not str Originally Posted by wmcbrine You might want to post more of your code to illustrate exactly what you've tried. Code: bitlist = ['AB', 'EC', 'CD', 'AB', 'ED', 'EB', 'DB', 'AB', 'EC'] for bit in bitlist: bitstring += r'\x' + bit bitout = open('bitout', 'wb') bitout.write(bitstring)
TypeError: must be bytes or buffer, not str
bitlist = ['AB', 'EC', 'CD', 'AB', 'ED', 'EB', 'DB', 'AB', 'EC'] for bit in bitlist: bitstring += r'\x' + bit bitout = open('bitout', 'wb') bitout.write(bitstring)
the binascii module can help: Code: import binascii bitlist = ['AB', 'EC', 'CD', 'AB', 'ED', 'EB', 'DB', 'AB', 'EC'] bytes = binascii.a2b_hex(''.join(bitlist)) bitout.write(bytes)
import binascii bitlist = ['AB', 'EC', 'CD', 'AB', 'ED', 'EB', 'DB', 'AB', 'EC'] bytes = binascii.a2b_hex(''.join(bitlist)) bitout.write(bytes)
if those byte represent values you may find http://docs.python.org/library/struct.html useful
Pitivi Video Editor Fundraiser - Ongoing crowdfunding campaigns - My software - Decay: LHC Zombie Film
Originally Posted by v1rati Code: bitlist = ['AB', 'EC', 'CD', 'AB', 'ED', 'EB', 'DB', 'AB', 'EC'] for bit in bitlist: bitstring += r'\x' + bit bitout = open('bitout', 'wb') bitout.write(bitstring) So, what you're doing here is creating strings that start with a literal backslash. These are not then evaluated into byte values. (Think about it -- at what point would that happen?) You might try something more like this: Code: for bit in bitlist: bitstring += chr(int(bit, 16))
for bit in bitlist: bitstring += chr(int(bit, 16))
Ubuntu Forums Code of Conduct