Mike Sassatelli
Mike Sassatelli

Reputation: 3

Export a list of lists to CSV file

So I've got an interesting problem that's holding me back. I've got a massive list that contains around 150 lists of length 28. Each of these small lists looks something like this:

['A', '1', 'item', 'item', 'item', 'item', 'item', 'item', '', '', '', '', '', '', '', 'item', 'item', 'item plus text, hi there', 'item and more items', 'item ', 'item', '  item', 'item', 'item ', 'item', 'item', 'item', '']

It's worth pointing out that each of those items is a string that contains anything from \n characters, nothing at all, commas, etc... The first two items in each list is something like A 1, A 2, B 1, etc. My delimiter for csv files is the | character. The issue I'm having is that when I try to write this data back to a csv file I'm either only able to put the entire list as a string into the very first column on each row (meaning it looks exactly like what I've included above) or put each item on it's own row.

Ideally what I need to accomplish is each small list within the large list being on its own row, with each item in the small list being in it's own cell on that row. So each row would utilize columns A-AB for one list. The code I have tried looks similar to:

with open("testFile.csv", "w") as csvfile:
    writer = csv.writer(csvfile, delimiter='|')
    for row in listOfRows: # Uses nested loops to access each item within
        for i in row:      # the small lists.
            writer.writerow([i])

I've tried a variation of this that writes the entire small list item but that ends up putting each small list into one cell in the first column. Anyone have any ideas on how to go about this?

Upvotes: 0

Views: 1023

Answers (2)

d_kennetz
d_kennetz

Reputation: 5359

Pandas can do this without you doing anything, really. I'll show you an example with your list just duplicated, so that you have each list in one row, utilizing columns a-ab (I think this is what you wanted):

import pandas as pd

a = [['A', '1', 'item', 'item', 'item', 'item', 'item', 'item', '', '', '', '', '', '', '', 'item', 'item', 'item plus text, hi there', 'item and more items', 'item ', 'item', '  item', 'item', 'item ', 'item', 'item', 'item', ''],
['A', '1', 'item', 'item', 'item', 'item', 'item', 'item', '', '', '', '', '', '', '', 'item', 'item', 'item plus text, hi there', 'item and more items', 'item ', 'item', '  item', 'item', 'item ', 'item', 'item', 'item', '']]

df = pd.DataFrame(a)

df.to_csv('./Desktop/goofy.csv', index=False, sep='|')

Then your csv file looks like this:

enter image description here

Blank columns correspond to '' in the list.

Upvotes: 1

Marcus
Marcus

Reputation: 3544

You should be able to use the writerows function of the csvwriter class to do this all at once without a loop.

with open("testFile.csv", "w") as csvfile:
    writer = csv.writer(csvfile, delimiter='|')
    writer.writerows(listOfRows)

Upvotes: 1

Related Questions