【问题标题】:How to convert a list of lists into a CSV file format? [duplicate]如何将列表列表转换为 CSV 文件格式? [复制]
【发布时间】:2019-12-12 13:29:29
【问题描述】:

如何在python中将列表列表转换为CSV文件格式?

这就是我所拥有的,列表列表:

[
    ['Node', 'Resource', 'Actual Number', 'Maximum Number Allowed', 'Usage'],
    ['node1', 'AuC Data Management', '5586618', '5820000', '95%'],
    ['node2', 'Enhanced Multi-Level Precedence and Pre-Emption Service (eMLPP)', '1', '3001', '0%']
    ...
]

我想要什么 csv:

Node,Resource,Actual Number,Maximum Number Allowed,Usage
node1,AuC Data Management,5586618,5820000,95%
node2,Enhanced Multi-Level Precedence and Pre-Emption Service (eMLPP),1,3001,0%
...

抱歉,自从我研究 python 以来已经有一段时间了,这就是我目前正在做的事情:

>>> x
[['Node', 'Resource', 'Actual Number', 'Maximum Number Allowed', 'Usage'], ['node1', 'AuC Data Management', '5586618', '5820000', '95%'], ['node2', 'Enhanced Multi-Level Precedence and Pre-Emption Service (eMLPP)', '1', '3001', '0%']]

>>> x[0]
['Node', 'Resource', 'Actual Number', 'Maximum Number Allowed', 'Usage']

此外,是否有带有一些代码的库/资源可以针对列表列表可能出现的各种排列进行这种转换?

可能的相关问题:
Python csv file writing a list of lists
Writing a Python list of lists to a csv file
CSV IO python: converting a csv file into a list of lists
Write a list of lists into csv in Python
Convert this list of lists in CSV

【问题讨论】:

标签: python csv


【解决方案1】:

使用csv 模块,它会为您提供支持。

import csv

with open('somefile.csv', 'w', encoding='utf8') as csv_out:
    writer = csv.writer(csv_out)
    rows = [
        ['Node', 'Resource', 'Actual Number', 'Maximum Number Allowed', 'Usage'],
        ['node1', 'AuC Data Management', '5586618', '5820000', '95%'],
        ['node2', 'Enhanced Multi-Level Precedence and Pre-Emption Service (eMLPP)', '1', '3001', '0%']
]
    writer.writerows(rows)

【讨论】:

    猜你喜欢
    • 2013-12-21
    • 1970-01-01
    • 2016-01-15
    • 2021-05-26
    • 1970-01-01
    • 2016-07-11
    • 1970-01-01
    • 2021-07-27
    • 2018-01-02
    相关资源
    最近更新 更多