【问题标题】:string - Python 3.5 write a bytes-like object is required, not 'str'string - Python 3.5 需要写一个类似字节的对象,而不是'str'
【发布时间】:2019-01-27 03:13:41
【问题描述】:

我的以下 python 代码适用于 Python 2,

只写一次标题

if header_written == False:
    header = out_data.keys()
    writer.writerow(out_data.keys()) # write headers
    header_written = True

写入值

writer.writerow(out_data.values()) #write rows
del out_data  #del object
del row_data #del dict object

但在 Python 3 中,它返回以下错误:

TypeError: 需要一个类似字节的对象,而不是 'str'

【问题讨论】:

    标签: string python-3.x types


    【解决方案1】:

    您必须将其转换为字节。你可以这样做。

    bytes = string.encode(encoding='UTF-8')
    

    更多信息在这里

    Best way to convert string to bytes in Python 3?

    【讨论】:

    • 谢谢!我将第一部分的第三行更改为:writer.writerow(out_data.keys().encode('utf-8')) 但以下错误消息显示:'odict_keys' object has no attribute 'encode'
    【解决方案2】:

    这是关于最初的部分。

    改变

    with open('r2.csv', 'r') as infile , open("output2.csv",'wb') as resultFile:
    

    with open('r2.csv', 'r') as infile , open("output2.csv",'w') as resultFile:
    

    【讨论】:

      猜你喜欢
      • 2016-11-27
      • 2018-06-01
      • 1970-01-01
      • 2017-08-31
      • 1970-01-01
      • 1970-01-01
      • 2017-03-05
      • 1970-01-01
      • 2016-01-05
      相关资源
      最近更新 更多