views:

27

answers:

1

I want to create an array.array object from a cStringIO object:

    import cStringIO, array

    s = """
    <several lines of text>
    """

    f = cStringIO.StringIO(s)
    a = array.array('c')
    a.fromfile(f, len(s))

But I get the following exception:

Traceback (most recent call last):  
  File "./myfile.py", line 22, in <module>  
    a.fromfile(f, len(s))  
TypeError: arg1 must be open file

It seems like array.array() is checking the type() of the first argument, which makes it incompatible with cStringIO (and StringIO for that matter). Is there any way to make this work?

+4  A: 

Why not use a.fromstring()? Since the StringIO buffer is entirely in memory, there is no benefit to trying to use a file api to read the bits from one memory location to another.

a = array.array('c')
a.fromstring(s)

If you are using StringIO for another reason (as a memory buffer, or as a file earlier on), then you can use StringIO's getvalue() function to get the string value.

Mike Axiak
Thanks! I'm parsing a file that's text interleaved with binary payloads, so in order to do this I had to use "a.fromstring(s[f.tell():bin_data_end])" and then move the StringIO forward with f.seek()
aaronstacy