【问题标题】:Python : How to write list to csv with N items per rowPython:如何将列表写入csv,每行有N个项目
【发布时间】:2019-12-22 11:49:45
【问题描述】:

我正在尝试将列表保存到 csv。我的代码是这样的:

import csv
list = ['John Doe', '51234512214', 'California', 'Student', 'Jane Doe', '1234123123', 'Canada', 'Student', 'Bill Gates', '4123123123211', 'New York', 'Student']

with open(export_file, 'wb') as myfile:
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    wr.writerow(list)
myfile.close()

问题

我想从每行 4 个项目的列表中创建 csv。我的例外 csv 输出是这样的:

如何用最好的 python 方法实现我预期的 csv 文件?

提前致谢。

【问题讨论】:

    标签: python csv export-to-csv


    【解决方案1】:

    你可以先创建一个函数来产生 n 大小的块:

    def chunks(lst, n):
        for i in range(0, len(lst), n):
            yield lst[i:i + n]
    

    然后将生成器中的每个块写入 CSV 文件:

    with open("output.csv", mode="w", newline="") as csv_out:
        csv_writer = writer(csv_out, quoting=QUOTE_ALL)
        for chunk in chunks(lst, 4):
            csv_writer.writerow(chunk)
    

    完整代码:

    from csv import writer, QUOTE_ALL
    
    lst = [
        "John Doe",
        "51234512214",
        "California",
        "Student",
        "Jane Doe",
        "1234123123",
        "Canada",
        "Student",
        "Bill Gates",
        "4123123123211",
        "New York",
        "Student",
    ]
    
    def chunks(lst, n):
        for i in range(0, len(lst), n):
            yield lst[i:i + n]
    
    with open("output.csv", mode="w", newline="") as csv_out:
        csv_writer = writer(csv_out, quoting=QUOTE_ALL)
        for chunk in chunks(lst, 4):
            csv_writer.writerow(chunk)
    

    输出.csv:

    "John Doe","51234512214","California","Student"
    "Jane Doe","1234123123","Canada","Student"
    "Bill Gates","4123123123211","New York","Student"
    

    【讨论】:

    • 也可以使用for chunk in zip(*[iter(lst)]*4):,它不需要chunks() 辅助函数。仍然是一个很好的答案。
    【解决方案2】:

    您可以将原始列表拆分为 4 个项目的子列表,并使用 writerows 将其写入一次:

    import csv
    data = ['John Doe', '51234512214', 'California', 'Student', 'Jane Doe', '1234123123', 'Canada', 'Student', 'Bill Gates', '4123123123211', 'New York', 'Student']
    rows = [data[i:i+4] for i in range(0, len(data), 4)]
    
    with open(export_file, 'w', newline='') as myfile:
        wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
        wr.writerows(rows)
    

    注意一些额外的变化:

    • 我将原始列表的名称从 list 更改为 data:您不应该使用 Python 内置函数的名称作为变量名(在这里,您将无法使用 list 进一步构建列表)
    • 您必须像使用 'wb' 那样以文本模式(默认)而不是二进制模式打开文件。
    • 我添加了newline='' 参数。正如csv 模块文档的最后所述:

    如果未指定 newline='',则在引用字段中嵌入换行符 将无法正确解释,并且在使用 \r\n 的平台上 linendings on write 额外的 \r 将被添加。它应该永远是 安全地指定 newline='',因为 csv 模块自己做 (通用)换行符处理。

    【讨论】:

      【解决方案3】:

      这里是单线器

      import pandas as pd
      import numpy as np
      
      your_list = ['John Doe', '51234512214', 'California', 'Student', 'Jane Doe', '1234123123', 'Canada', 'Student', 'Bill Gates', '4123123123211', 'New York', 'Student']
      
      pd.DataFrame(np.reshape(np.array(your_list), (int(len(your_list)/4), 4))).to_csv('your_list_as.csv', index = False, header = False)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-25
        • 2017-11-20
        • 2012-01-02
        • 2018-04-02
        • 2017-05-11
        相关资源
        最近更新 更多