I have a function that's reading a content object into a pandas dataframe.
import pandas as pd
from cStringIO import StringIO, InputType
def create_df(content):
assert content, "No content was provided, can't create dataframe"
if not isinstance(content, InputType):
content = StringIO(content)
content.seek(0)
return pd.read_csv(content)
However I keep getting the error TypeError: StringIO() argument 1 must be string or buffer, not cStringIO.StringIO
I checked the incoming type of the content prior to the StringIO() conversion inside the function and it's of type str. Without the conversion I get an error that the str object does not have a seek function. Any idea whats wrong here?
You only tested for
InputType, which is acStringIO.StringIO()instance that supports reading. You appear to have the other type,OutputType, the instance created for an instance that supports writing to:You'd need to test for both types, just use a tuple of the two types as the second argument to
isinstance():or, and this is the better option, test for
readandseekattributes, so you can also support regular files:or you could just test for strings and [buffers](https://docs.python.org/2/library/functions.html#buffer(, since those are the only two types that
StringIO()can support:This has the added bonus that any other file object in the Python library, including compressed files and
tempfile.SpooledTemporaryFile()andio.BytesIO()will also be accepted and work.