Reputation: 75
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
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