在python中写入输出csv文件
我正在尝试将列表写入csv文件,以便正确格式化。我从其他堆栈溢出帖子中读到,下面的方法是正确的(为了保留我想要打印出来的逗号等),但这对我来说不起作用 它不是在自己的csv行中打印每个列表(在在python中写入输出csv文件,python,Python,我正在尝试将列表写入csv文件,以便正确格式化。我从其他堆栈溢出帖子中读到,下面的方法是正确的(为了保留我想要打印出来的逗号等),但这对我来说不起作用 它不是在自己的csv行中打印每个列表(在final_list中),而是在一个长的连续行中,每个单元格只打印一个列表,即没有换行。关于我能做什么有什么想法吗 import csv final_list = ['country name', 'average urban population ratio', 'average life expec
final_list
中),而是在一个长的连续行中,每个单元格只打印一个列表,即没有换行。关于我能做什么有什么想法吗
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)
您需要将数据拆分为标题,然后是行(数据)
我认为您可能正在使用Python2.x,但这可能会有所帮助。我填写了一个虚拟的
stats\u 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']
而且
final_list.append([key, value[4], value[5], value[0], value[1]])
第一个是字符串列表,第二个是列表列表列表。第二个是正确的-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
在哪里定义了统计数据?
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