-3

I have added multiple lists to a csv with the following code:

with open(r'my\file\path.csv', 'w', newline='') as f:
    spamwriter = csv.writer(f, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
    data = list(zip(First_Name, Last_Name, Emails, Phones, Status))
    for row in data:
        row = list(row)
        spamwriter.writerow(row)

However, the csv doesn't contain the headers:

['First_Name', 'Last_Name', 'Emails', 'Phones', 'Status']

How do I get the headers in the first row of the CSV? I need them to do some logic about which email addresses to send to.

3
  • 2
    Before the for loop, write the header row. Commented Jul 18, 2020 at 17:54
  • Please refer to any tutorial on dealing with CSV files from Python. Commented Jul 18, 2020 at 17:54
  • 1
    Does this answer your question? Pythonically add header to a csv file Commented Jul 18, 2020 at 18:03

1 Answer 1

0

I found a way around it. I simply appended to header to each of the empty lists before going through each row. The header will print once at the top of each column in the csv.

Emails = []
Emails.append('Emails')
Status = []
Status.append('Status')
First_Name = []
First_Name.append('First_Name')
Last_Name = []
Last_Name.append('Last_Name')
Phones = []
Phones.append('Phones')

transactions = dict["transactions"]
for transaction in transactions:
    email = transaction['order']['description']['billingAddress']['email']
    Emails.append(email)
    status = transaction['order']['description']['subscription']['status']
    Status.append(status)
    first_name = transaction['order']['description']['billingAddress']['firstName']
    First_Name.append(first_name)
    last_name = transaction['order']['description']['billingAddress']['lastName']
    Last_Name.append(last_name)
    phone_number = transaction['order']['description']['billingAddress']['phone']
    Phones.append(phone_number)

with open(r'my\file\path.csv', 'w', newline='') as f:
    spamwriter = csv.writer(f, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
    data = list(zip(First_Name, Last_Name, Emails, Phones, Status))
    for row in data:
        row = list(row)
        spamwriter.writerow(row)
    f.close()
Sign up to request clarification or add additional context in comments.

2 Comments

I recommend you to read about pandas package. It is a package for dealing with data, it will make all of your code much more simpler. Including reading from / writing to csv files
Did you see Craig's comment? Literally all you need to do is write the header row before the for loop. spamwriter.writerow(['First_Name', 'Last_Name', 'Emails', 'Phones', 'Status'])

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.