我正在尝试将列表写入csv文件,以便正确格式化。我从其他堆栈溢出帖子中读到以下是正确的方法,(为了保留我想要打印的逗号等),但这对我不起作用。
它不是在自己的csv行中打印每个列表(在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)
答案 0 :(得分:1)
您需要将数据拆分为标题,然后拆分行(数据)。
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
答案 1 :(得分:0)
我认为你可能在Python 2.x上,但也许这会有所帮助。我填写了一个虚拟stats_dict
并重新排列了值的索引(我称之为v
)。我还为你的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']]
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)
答案 2 :(得分:0)
您的代码几乎就是现货。您只需要看看在这两行中评估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