【问题标题】:Writing two lists one after after another to csv file using python使用python将两个列表一个接一个地写入csv文件
【发布时间】:2018-07-12 09:39:26
【问题描述】:

我有两个列表,一个包含 Date,另一个包含 Rf

Date = ['July 12', 'July 13', 'July 14', 'July 15', 'July 16']
rf = ['12', '16', '18', '10', '4']

out = open('out.csv','ab')
writer = csv.writer(out)
writer.writerow(Date)
writer.writerow(rf)

但是 csv 中的输出并不像

Jul 12  Jul 13  Jul 14  Jul 15  Jul 16  
12      16      18      10      4

【问题讨论】:

  • 考虑使用with open.. 构造来避免像现在这样的错误 - 不关闭文件
  • 对不起,我忘了最后一行关闭了。close()

标签: python python-2.7 list csv


【解决方案1】:

在 Python 2.x 中,您可以将 io.open 与参数 mode='w'newline='' 一起使用。您还应该使用with 语句:

Date = ['July 12', 'July 13', 'July 14', 'July 15', 'July 16']
rf = ['12', '16', '18', '10', '4']

import csv, io

with io.open('out.csv', 'wb', newline='') as out:
    writer = csv.writer(out)
    writer.writerow(Date)
    writer.writerow(rf)

【讨论】:

  • @gi.rajan,好的.. 你发现上面有什么问题。 with 不是 Python 3.x 独有的。
  • 现在出现错误TypeError: must be unicode, not str。我试过with io.open('out.csv', mode='w', newline='', encoding='utf8') as out 但没用
  • @gi.rajan,查看更新,您可能需要二进制模式,即mode='wb'
  • 是的,我明白了...感谢您的帮助。
猜你喜欢
  • 2021-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-01
  • 2023-04-07
  • 2014-11-22
  • 2015-01-07
相关资源
最近更新 更多