Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top