Python将列表写入csv,无法将值放入列中

2024-03-29 12:38:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下国家名单:

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

我正在尝试将此写入csv:

^{pr2}$

但是,在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


Tags: ofcsv代码importoutputitemcountrywrite
3条回答

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

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])

尝试以下操作:

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, ))

试试这个:

import csv

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

with open('temp.csv', 'w') as output_write:
    csvout = csv.writer(output_write, lineterminator='\n')
    for country in countries:
         csvout.writerow([country])

enter image description here

相关问题 更多 >