[英]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. 我可以按照自己的意愿写第一个项目列表,以使第一列下降,但是我很难使第二个列表写入csv文件中的第三[2]列。 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. 当前,这会将其写入csv文件,并且这两个元素的所有元素都在first [0]列中列出。 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. iv围绕这件事玩了一些,但是却很难在csv文件中得到它。
Take a look at the zip function. 看一下zip功能。
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. 请注意,您的列表应具有相同的长度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.