【问题标题】:List to CSV writing is not working in Python 2.7CSV 写入列表在 Python 2.7 中不起作用
【发布时间】:2020-06-09 18:30:40
【问题描述】:

我已使用模块 3to2 将我的 python3 代码转换为 python2,但现在无法写入 CSV 文件。

TypeError: must be unicode, not str 转换后的代码

 def writeCSV(self,filepath,data):
        with open(filepath, u'a', newline=u'') as file:
            writer = csv.writer(file)
            writer.writerow(data)

传递的数据是['10/06/2020 04:28:57 AM', u'HCL Docker', u'Down'] .我可以知道如何解决这个问题吗?

【问题讨论】:

    标签: list python-2.7 export-to-csv


    【解决方案1】:

    在列表中:

    ['10/06/2020 04:28:57 AM', u'HCL Docker', u'Down']
    

    如错误消息所述,第一项必须是unicode,而不是str。如您所见,Unicode 以u 为前缀,例如:u'HCL Docker'

    所以你应该确保data 中的每一项都是unicode。您可以像这样将所有内容转换为unicode

    writer.writerow(map(unicode, data))
    

    【讨论】:

    • 我已经试过了,但是结果是一样的
    • 更改为 [u'10/06/2020 13:14:43 PM', u'HCL Docker', u'Down']
    猜你喜欢
    • 2020-02-01
    • 1970-01-01
    • 2018-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-29
    • 2021-11-09
    相关资源
    最近更新 更多