1

I scraped information, and I have it stored in multiple lists:

list1 = [item1, item2,item3...]
list2 = [i1,i2,i3...]
list3 = [it1,it2,it3..]

How do I write code that will save it to save it as a CSV file so that when I download it in Excel and it looks like the following?

Column 1 Column 2 Column 3
item1      i1        it1
item2      i2        it2

2 Answers 2

3

Use csv:

import csv

list1 = ['1','2','3']
list2 = ['4','5','6']

with open('file.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(list1)
    writer.writerow(list2)

This will write the contents of the lists into each row of the csv. It's unclear to me if you want header names and an index column as well. Depending on the actual problem you're facing, it could be easier to just use pandas, which will give you the names of the rows in the first column as well as column names:

import pandas as pd

list1 = ['1','2','3']
list2 = ['4','5','6']

df = pd.DataFrame({'list1': list1,
                   'list2': list2})

df.transpose().to_csv('file.csv')
Sign up to request clarification or add additional context in comments.

Comments

1

Python's zip built-in is a function that takes N iterators as input (like your N lists), and returns an iterator that yields the first items in each iterator at each time - and can be used in a for statement.

The final effect is that it transposes a set of lists, just like what you need:

import csv

# define lists:
...

with open("output.csv", "wt") as file:
    writer = csv.writer(file)
    writer.writerow(["column1", column2", ...]
    for row in zip(list1, list2, list3,...):
         writer.writerow(row)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.