[英]Writing output csv file python
我正在嘗試將列表寫入csv文件中,以便其正確格式化。 我從其他堆棧溢出文章中了解到,以下是這樣做的正確方法(以保留要打印的逗號等),但這對我不起作用。
final_list
在自己的csv行中打印每個列表(在final_list
), 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)
您需要將數據拆分為標題,然后拆分為(數據的)行。
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
我認為您可能正在使用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)
您的代碼幾乎可以使用了。 您只需要查看這兩行中如何評估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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.