-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.

Matt
  • 5
  • 1
  • 3
  • 2
    Before the for loop, write the header row. – Craig Jul 18 '20 at 17:54
  • Please refer to any tutorial on dealing with CSV files from Python. – Prune Jul 18 '20 at 17:54
  • 1
    Does this answer your question? [Pythonically add header to a csv file](https://stackoverflow.com/questions/20347766/pythonically-add-header-to-a-csv-file) – Roim Jul 18 '20 at 18:03

1 Answers1

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()
Matt
  • 5
  • 1
  • 3
  • 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 – Roim Jul 18 '20 at 18:05
  • 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'])` – alani Jul 18 '20 at 18:07