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

问题描述 投票:-1回答:1

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

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() argument 1 must be string or buffer, not cStringIO.StringIO

我在函数内部的StringIO()转换之前检查了内容的传入类型,它的类型为str。没有转换,我得到str对象没有搜索功能的错误。这里有什么想法吗?

python python-2.7 pandas stringio cstringio
1个回答
1
投票

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

>>> import cStringIO
>>> finput = cStringIO.StringIO('Hello world!')  # the input type, it has data ready to read
>>> finput
<cStringIO.StringI object at 0x1034397a0>
>>> isinstance(finput, cStringIO.InputType)
True
>>> foutput = cStringIO.StringIO()  # the output type, it is ready to receive data
>>> foutput
<cStringIO.StringO object at 0x102fb99d0>
>>> isinstance(foutput, cStringIO.OutputType)
True

您需要测试这两种类型,只需使用两种类型的元组作为isinstance()的第二个参数:

from cStringIO import StringIO, InputType, OutputType

if not isinstance(content, (InputType, OutputType)):
    content = StringIO(content)

或者,这是更好的选择,测试readseek属性,所以你也可以支持常规文件:

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)

或者你可以只测试字符串和[缓冲](https://docs.python.org/2/library/functions.html#buffer(,因为这是StringIO()可以支持的唯一两种类型:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.