写入输出csv文件python

2024-06-17 17:35:45 发布

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

我正在尝试将一个列表写入一个csv文件,以使其格式正确。我从其他的堆栈溢出帖子中读到,下面是正确的方法(为了保留我想打印出来的逗号等等),但这对我来说不起作用。在

它不是打印每个列表(在final_list)在自己的csv行中,而是在一个长的、连续的行中打印每个单元格一个列表,也就是没有换行符。你知道我能做什么吗?在

import csv 

final_list = ['country name', 'average urban population ratio', 'average life expectancy', 'sum of total population in all years', 'sum of urban population in all years']

for key, value in sorted(stats_dict.iteritems()):
    if value[5] != 0:
        final_list.append([key, value[4], value[5], value[0], value[1]])

with open("output.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerow(final_list)

Tags: ofcsvkeyin列表valuealllist
3条回答

您需要将数据拆分为标题,然后再拆分(数据的)行。在

header = ['country name', 'average urban population ratio', 'average life expectancy', 'sum of total population in all years', 'sum of urban population in all years']

final_list = []

for key, value in sorted(stats_dict.iteritems()):
    if value[5] != 0:
        final_list.append([key, value[4], value[5], value[0], value[1]])

with open('output.csv', 'wb') as f:
    writer = csv.writer(f, delimiter=',')
    writer.writerow(header)
    writer.writerows(final_list) # note .writerows

# f.close() - not needed, the with statement closes the file for you

我想你可能在Python2.x上,但也许这会有所帮助。我填充了一个虚拟的stats_dict并重新排列了值的索引(我称之为v)。我还为你做了一个列表列表。在

final_list = [['country name', 'average urban population ratio', 'average life expectancy', 'sum of total population in all years', 'sum of urban population in all years']]
stats_dict = {'Key': ['USA', 250000000, 75, 1000000, 1000001]}
for k, v in sorted(stats_dict.items()):
    if v[4] != 0:
        final_list.append([v[0], v[1], v[2], v[3], v[4]])

with open('output.csv', 'w', newline='') as f:
    writer = csv.writer(f, delimiter=',')
    writer.writerows(final_list)

你的代码几乎准确无误。您只需要看看如何在这两行中计算final_list之间的差异:

final_list = ['country name', 'average urban population ratio', 'average life expectancy', 'sum of total population in all years', 'sum of urban population in all years']

还有。。。在

^{pr2}$

第一个是字符串列表,第二个是列表列表。第二个是正确的-CSV文件中的每一行都应该是一个列表。要更正代码,请将第一行(标题)也列为列表:

import csv 

# note that we have really only changed the next line
final_list = [['country name', 'average urban population ratio', 'average life expectancy', 'sum of total population in all years', 'sum of urban population in all years']]

for key, value in sorted(stats_dict.iteritems()):
    if value[5] != 0:
        final_list.append([key, value[4], value[5], value[0], value[1]])

with open("output.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(final_list) # we use writerows not writerow

相关问题 更多 >