-3

How to convert a list of lists into a CSV file format in python?

This is what I have, a list of lists:

[
    ['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%']
    ...
]

What I want 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%
...

Apologies but its been a while since I looked at python and this is what I am working on so far:

>>> 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']

In addition, is there a library/resource out there with some code that can make this conversion for the various permutations that the list of lists could come in?

Possible related question:
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

martineau
  • 99,260
  • 22
  • 139
  • 249
HattrickNZ
  • 3,493
  • 12
  • 40
  • 82
  • 2
    Asking for libraries, tools, or off-site resources recommendation is off-topic in here. Also, StackOverflow expects you to [try to solve your own problem first](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users), as your attempts help us to better understand what you want. Please edit the question to show what you've tried, and show a specific roadblock you're running into with [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – Andreas Aug 05 '19 at 02:23

1 Answers1

1

Use the csv module it's got your back.

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)
monkut
  • 36,357
  • 21
  • 109
  • 140