Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python StringIO()参数1必须是字符串或缓冲区,而不是cStringIO.StringIO_Python_Python 2.7_Pandas_Stringio_Cstringio - Fatal编程技术网

Python StringIO()参数1必须是字符串或缓冲区,而不是cStringIO.StringIO

Python StringIO()参数1必须是字符串或缓冲区,而不是cStringIO.StringIO,python,python-2.7,pandas,stringio,cstringio,Python,Python 2.7,Pandas,Stringio,Cstringio,我有一个函数,它将内容对象读入数据帧 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(con

我有一个函数,它将内容对象读入数据帧

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)
但是,我不断得到错误
TypeError:StringIO()参数1必须是字符串或缓冲区,而不是cStringIO.StringIO


在函数内部进行StringIO()转换之前,我检查了内容的传入类型,它的类型为
str
。如果没有转换,我会得到一个错误,str对象没有seek函数。知道这里出了什么问题吗?

您只测试了
InputType
,这是一个支持读取的
cStringIO.StringIO()
实例。您似乎有另一种类型,
OutputType
,即为支持写入的实例创建的实例:

或者,这是更好的选择,测试
read
seek
属性,这样您也可以支持常规文件:

if not (hasattr(content, 'read') and hasattr(content, 'seek')):
    # if not a file object, assume it is a string and wrap it in an in-memory file.
    content = StringIO(content)
或者您可以只测试字符串和[buffers](),因为这是
StringIO()
可以支持的唯一两种类型:

if isinstance(content, (str, buffer)):
    # wrap strings into an in-memory file
    content = StringIO(content)

这增加了Python库中任何其他文件对象的额外好处,包括压缩文件和
tempfile.SpooledTemporaryFile()
io.BytesIO()
也将被接受并工作。

InputType
是在
cStringIO
中定义的两种类型之一。可能您有一个
OutputType
实例。奇怪的是,我将其更改为OutputType,它工作了。但是相同的函数以前一直在使用InputType,直到我更改了代码中无法理解的某些内容这是因为
StringIO('content')
创建
InputType
实例,而
StringIO()
(无参数)创建
OutputType
实例。您需要对这两种类型进行测试。
if not (hasattr(content, 'read') and hasattr(content, 'seek')):
    # if not a file object, assume it is a string and wrap it in an in-memory file.
    content = StringIO(content)
if isinstance(content, (str, buffer)):
    # wrap strings into an in-memory file
    content = StringIO(content)