Ethan Venencia
Ethan Venencia

Reputation: 75

Writing to a csvFile using two lists. How do i write each list to two different columns

I can write the first list of items to go down the first column how i want it but im struggling to get the second list to write to the third[2] column in the csv file. This i what i currently have. This just writes the second list below the first as i have just repeated the action of the first list.

firstHalf = ["Dad", "Mom", "nan"]
secondHalf = ["Brother", "Sister", "Cousin"]
    with open('MyFile.csv', 'w', newline='') as csv_file:
        csv_app = csv.writer(csv_file, delimiter=',')
        for player in firstHalf:
            csv_app.writerow([player])
        for player1 in secondHalf:
            csv_app.writerow([player1])

This currently writes this to the csv file with all the elements of both list down the first[0] column. i want the first list down the first column but second list down the third column.

Iv played around this a few things but struggling to get it how i want in the csv file.

Upvotes: 0

Views: 215

Answers (1)

tidylobster
tidylobster

Reputation: 723

Take a look at the zip function.

firstHalf = ["Dad", "Mom", "nan"]
secondHalf = ["Brother", "Sister", "Cousin"]

with open('text.csv', 'w', newline='') as file:
    csv_app = csv.writer(file, delimiter=',')
    for one, two in zip(firstHalf, secondHalf):
        csv_app.writerow([one, None, two])

Mind, that your lists should be of the same length.

Upvotes: 1

Related Questions