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

时间:2019-08-05 02:20:00

标签: python csv

如何在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

1 个答案:

答案 0 :(得分: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)