【问题标题】:Most efficient way of writing a list (of lists of lists) to a csv in Python?在Python中将列表(列表列表)写入csv的最有效方法?
【发布时间】:2015-06-29 05:27:52
【问题描述】:

给定(伪代码):

for city in cities:
  for info in city:
      #add some stuff to a list
   #add each list to a list (creating a list of lists)

  with open('file.csv', 'ab') as csvfile:
      writer = csv.writer(csvfile)
      writer.writerows(the list of lists) #in order of list

所以我打开每个城市的文件并附加每个城市的每个列表 列表列表。实现这一目标的更有效(更快)的方法是什么?

【问题讨论】:

  • 你想再次使用python中的列表还是只存储输出
  • 好问题。不,一旦我写入 csv,我就不再需要这些列表了。 (这适用于 list-of-lists-of-lists 中的每个列表)。
  • 使用 csvwriter 模块写入 csv 文件,能否提供列表示例的列表
  • 示例更新显示我已经在使用 csv.writer
  • 我已经认为这个写法是最有效的写法是什么你面临的问题或者不是每次都写一次你可以写一次

标签: python list file python-2.7 file-io


【解决方案1】:

我觉得我没有抓住重点,但是只是简单地打开文件一次然后在每个城市循环结束时写入不只是简单的重新排列吗?

with open('file.csv', 'w') as csvfile:
    writer = csv.writer(csvfile)

    for city in cities:
        for info in city:
            #add some stuff to a list
        #add each list to a list (creating a list of lists)

    writer.writerows(the list of lists)

【讨论】:

    【解决方案2】:

    如果您不需要“人工”读取文件,您可以使用 pickle 模块并将二维列表转储到文件中。然后,您的程序可以在以后读回数据,并且数据结构将完好无损。

    【讨论】:

    • 或者,如果数据是完全文本的,JSON 模块。比泡菜更便携、更安全。
    • 我应该在标题中指定 csv 而不是 file,以表明是的,该文件需要是人类可读的。标题已更新。
    • pickle 是应该避免的,而不是被接受的。
    猜你喜欢
    • 2013-07-16
    • 2019-06-22
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多