juju
juju

Reputation: 994

Python 3.6. How to iterate over multiple list in a for loop and write them to a CSV File using DictWriter()

I am trying to iterate over multiple lists and save them as CSV files to open in a spreadsheet, with the first list adding it's values to columns 1, 2, and 3, and the second list adding it's values to columns 4, 5, 6. I am instead getting line 1 of list one the len(list 2) amount of times and then the second line of list 2 the same and so forth. List 2 prints out as normal and then prints again once the second line of list 1 finally prints. Hopefully I explained this well enough.

ixl_file = open('ixalan.txt', 'r')
ixl_card = []
ixl_price = []
ixl_quantity = []
for line in ixl_file:
    info = line.split("|")
    ixl_card.append(info[0])
    ixl_price.append(info[1])
    ixl_quantity.append(info[2])
ixl_file.close()

kal_file = open('kaladesh.txt', 'r')
kal_card = []
kal_price = []
kal_quantity = []
for line in kal_file:
    info = line.split("|")
    kal_card.append(info[0])
    kal_price.append(info[1])
    kal_quantity.append(info[2])
kal_file.close()

with open('card_kingdom.csv', 'w', newline='') as ixl:
        fieldnames = ['Col 1', 'Col 2', 'Col 3', 'Col 4', 'Col 5', 'Col 6']
    writer = csv.DictWriter(ixl, fieldnames=fieldnames)
    writer.writeheader()

"""Below is where I am having trouble add these two list in the desired format"""

    for a,b in itertools.product(range(len(ixl_card)), range(len(kal_card))):
        writer.writerow({'Col 1': ixl_card[a],
                         'Col 2': ixl_price[a],
                         'Col 3': ixl_quantity[a],
                         'Col 4': kal_card[b],
                         'Col 5': kal_price[b],
                         'Col 6': kal_quantity[b]
                       })

Your help would be much appreciated! Let me know if you need the rest of the code. Thanks!!

Upvotes: 0

Views: 310

Answers (1)

Martin Evans
Martin Evans

Reputation: 46779

This could be done using just a normal CSV writer as all of your columns appear to be in the same order:

import csv    

with open('ixalan.txt', newline='') as f_ixalan:
    ixalan = list(csv.reader(f_ixalan, delimiter='|'))

with open('kaladesh.txt', newline='') as f_kaladesh:
    kaladesh = list(csv.reader(f_kaladesh, delimiter='|'))

with open('card_kingdom.csv', 'w', newline='') as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(['Col 1', 'Col 2', 'Col 3', 'Col 4', 'Col 5', 'Col 6'])

    for p1, p2 in zip(ixalan, kaladesh):
        csv_output.writerow(p1 + p2)

Also your two .txt files can be read using a csv.reader() by specifying a | for the delimiter. Using zip() takes one row from each of your two input lists, these can then be combined and written to your output CSV.

Upvotes: 1

Related Questions