【问题标题】:StringIO() argument 1 must be string or buffer, not cStringIO.StringIOStringIO() 参数 1 必须是字符串或缓冲区,而不是 cStringIO.StringIO
【发布时间】:2019-02-17 04:28:15
【问题描述】:

我有一个将内容对象读入熊猫数据框的函数。

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 对象没有搜索功能的错误。知道这里有什么问题吗?

【问题讨论】:

  • InputTypecStringIO 中定义的两种类型之一。大概你有一个OutputType 实例。
  • 奇怪,我将其更改为 OutputType 并且它起作用了。但是在我更改了代码中的某些内容之前,相同的函数一直在使用 InputType,但我无法弄清楚它是什么。谢谢
  • 这是因为StringIO('content') 创建了InputType 实例,而StringIO()(无参数)创建了OutputType 实例。您需要测试两种类型

标签: python python-2.7 pandas stringio cstringio


【解决方案1】:

您只测试了InputType,这是一个支持阅读的cStringIO.StringIO() 实例。您似乎拥有 other 类型 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

您需要测试 both 类型,只需使用这两种类型的元组作为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)

或者您可以只测试字符串和 [buffers](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() 也将被接受和工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多