我有这个国家名单:
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中的行而不是列中。有人可以让我知道如何改变吗?
提前致谢!
我遵循了以下一些建议,输出行之间有空行:
我使用的代码:
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, ))
找到关于空行的相关帖子:
答案 0 :(得分:2)
如果要将每个项目写入单独的行,则必须遍历列表:
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])
答案 1 :(得分:1)
尝试以下方法:
country = ['Togo', 'Nauru', 'Palestine, State of', 'Malawi']
with open('temp.csv', 'wt') as output_write:
csvout = csv.writer(output_write, lineterminator='\n')
for item in country:
csvout.writerow((item, ))
答案 2 :(得分:1)