issue with struct.unpack

MRAB python at mrabarnett.plus.com
Tue Aug 28 19:36:20 EDT 2012


On 29/08/2012 00:01, 9bizy wrote:> On Tuesday, 28 August 2012 23:49:54 
UTC+1, MRAB  wrote:
 >> On 28/08/2012 23:34, 9bizy wrote:
 >> > This is what I have to reproduce the challenge I am having below:
 >> >
 >> > import csv
 >> > import struct
 >> >
 >> > data = []
 >> >
 >> > for Node in csv.reader(file('s_data.xls')):
 >>
 >> That tries to read the file as CSV, but, judging from the extension,
 >> it's in Excel's format. You don't even use what is read, i.e. Node.
 >>
 >> >      data.append(list((file('s_data.xls'))))
 >> >
 >> That opens the file again and 'list' causes it to read the file as
 >> though it were a series of lines in a text file, which, as I've said,
 >> it looks like it isn't. The list of 'lines' is appended to the list
 >> 'data', so that's a list of lists.
 >> >
 >> >      data = struct.unpack('!B4HH', data)
 >> >      print "s_data.csv: ", data
 >> >
 >> > I tries so many format for the struct.unpack but I got this errors:
 >> >
 >> > Traceback (most recent call last):
 >> >
 >> >      data = struct.unpack('!B4HH', data)
 >> > struct.error: unpack requires a string argument of length 11
 >> >
 >> [snip]
 >> It's complaining because it's expecting a string argument but you're
 >> giving it a list instead.
 >
 > How do I then convert data to a string argument in this case?
 >
The question is: what are you trying to do?

If you're trying to read an Excel file, then you should be trying the
'xlrd' module. You can find it here: http://www.python-excel.org/

If your trying to 'decode' a binary file, then you should open it in
binary mode (with "rb"), read (some of) it as a byte string and then
pass it to struct.unpack.



More information about the Python-list mailing list