【问题标题】:Python 2.x to 3.x converted code fails in IO.StringIO conversionPython 2.x 到 3.x 转换的代码在 IO.StringIO 转换中失败
【发布时间】:2018-03-06 13:55:12
【问题描述】:

python 2.x 代码

sdata = StringIO.StringIO(c.data)

python 3.x 代码

sdata = io.StringIO(c.data)

完整代码

def downloadCSV(c, d):
    filename = c.getFilename(d)
    reqstr = c.getReqStr(d)

    print(("Downloading %s ..." % (filename)))
    if c.getResponse(reqstr) == -1:
        return -1
    sdata = io.StringIO(c.data)
    z = zipfile.ZipFile(sdata)

错误:

Traceback (most recent call last):
  File "xxx.py", line 166, in <module>
    main(sys.argv[1:])
  File "xxxx.py", line 158, in main
    getMonth(c, args[1], args[2])
  File "xxxx.py", line 133, in getMonth
    if downloadCSV(c, d) > -1:
  File "xxxx.py", line 73, in downloadCSV
    sdata = io.StringIO(c.data)
TypeError: initial_value must be str or None, not bytes

3.x python 版本正确导入,sdata 的转换应该在这里自动发生?为什么会出现上述错误,以及在 python3.x 中纠正此错误的方法是什么。尝试了此论坛中发布的其他答案,但在这种情况下似乎没有任何效果。

【问题讨论】:

    标签: python python-3.x io


    【解决方案1】:

    Python 3 现在对strbytes 产生了影响。

    您的请求返回二进制数据,因此为了能够将其存储在 io 对象中,您必须创建 BytesIO 对象而不是 StringIO 对象。所以:

    sdata = io.BytesIO(c.data) 
    

    请注意,代码仍然与 Python 2 兼容。

    【讨论】:

      猜你喜欢
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-13
      • 2022-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多