gpt4 book ai didi

Python 将列表写入 csv,不能将值放入列中

转载 作者:行者123 更新时间:2023-11-28 22:22:54 25 4
gpt4 key购买 nike

我有这个国家列表:

country = ['Togo', 'Nauru', 'Palestine, State of', 'Malawi']

我正在尝试将其写入 csv:

with open('temp.csv', 'wt') as output_write:
csvout = csv.writer(output_write)
csvout.writerow(country)
output_write.close()

但是输出将值放入行而不是 csv 中的列。有人可以告诉我如何更改它吗?

提前致谢!


我遵循了下面的一些建议,输出的行之间有空行:

enter image description here

我使用的代码:

import csv
country = ['Togo', 'Nauru', 'Palestine, State of', 'Malawi']
with open('temp.csv', 'wt') as output_write:
csvout = csv.writer(output_write)
for item in country:
csvout.writerow((item, ))

更新:

我想出了我得到空行的原因,因为每一行都是因为 Windows 以不同方式解释新行。最终对我有用的代码是:

import csv
country = ['Togo', 'Nauru', 'Palestine, State of', 'Malawi']
with open('temp.csv', 'w', newline = '') as output_write:
csvout = csv.writer(output_write)
for item in country:
csvout.writerow((item, ))

找到一个关于空行的相关帖子:

python empty row

最佳答案

如果要将每个项目写入单独的行,则必须遍历列表:

import csv

country = ['Togo', 'Nauru', 'Palestine, State of', 'Malawi']

with open('temp.csv', 'wt') as output_write:
csvout = csv.writer(output_write, delimiter=',')
for c in country:
csvout.writerow([c])

关于Python 将列表写入 csv,不能将值放入列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47404738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com