2

I have multiple lists need write into a csv file with custom headers.

An example I have 3 lists as below.

a = ["Item A", "Item B", "Item C", "Item D"]
b = ["Price A", "Price B", "Price C", "Price D"]
c = ["Stock A", "Stock B", "Stock C", "Stock D"]

I tried below

import csv


a = ["Item A", "Item B", "Item C", "Item D"]
b = ["Price A", "Price B", "Price C", "Price D"]
c = ["Stock A", "Stock B", "Stock C", "Stock D"]

c = zip(a, b, c)


with open("test.csv", "w") as f:
    writer = csv.writer(f)
    writer.writerows(c)
    # writer.writerows(c)  

But I want them to show as below

enter image description here

4
  • 3
    Have you tried writing any code yet? If not, this should get you started docs.python.org/3/library/csv.html don't just expect people to write code for you! stackoverflow.com/help/how-to-ask Commented May 1, 2020 at 19:41
  • @L.Clarkson, Thanks for advice, I rarely post the question. Yes, I tried use csv.writer() with either writerows or writerow, the results not what I expected. Commented May 1, 2020 at 20:22
  • Can you edit your question to include the code you have tried? Commented May 1, 2020 at 20:32
  • Added, can you help look into it? Commented May 1, 2020 at 20:42

2 Answers 2

3

I like to use pandas for this using to_csv:

import pandas as pd

a = ["Item A", "Item B", "Item C", "Item D"]
b = ["Price A", "Price B", "Price C", "Price D"]
c = ["Stock A", "Stock B", "Stock C", "Stock D"]

data = {'Product': a,
         'List Price': b,
         'In Stock': c}

df = pd.DataFrame.from_dict(data)

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

2 Comments

you shouldn't waste your time on this type of questions where they don't show any efforts and just make stackoverflow as questions spam
@jayveesea Thanks for sharing the codes, I will look into the pandas module, I'm new in python.
1
import csv


a = ["Item A", "Item B", "Item C", "Item D"]
b = ["Price A", "Price B", "Price C", "Price D"]
c = ["Stock A", "Stock B", "Stock C", "Stock D"]



with open("test.csv", "w", newline='') as f:
    writer = csv.writer(f)
    for i in range(len(a)):
        content = [a[i], b[i], c[i]]
        writer.writerow(content)

1 Comment

Thanks a lot, that's what I need, but seems you miss the headers, I added a header before the for loop header = ['Product', 'List Price', 'Stock'] writer.writerow(header), after then the result is what I expected.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.