简体   繁体   English

将解压元组列表写入 CSV

[英]Writing a list of unpacked tuples to CSV

I am trying to write a list of tuples (which is not flat) into a CSV.我正在尝试将元组列表(不平坦)写入 CSV。 So for example the input would be:因此,例如输入将是:

[(('temperature', 42), ('date', datetime.date(2017, 1, 22)), ('locations', ('Berlin', 'Paris')), ('weather', 'sunny')), 
(('temperature', -42), ('date', datetime.date(2017, 1, 22)), ('locations', ('Marseille', 'Moscow')), ('weather', 'cloudy'))]

and output should be和 output 应该是

temperature,date,locations,weather
42,01/22/2017,"Berlin,Paris",sunny
-42,01/22/2017,"Marseille,Moscow",cloudy

However what I am getting is但是我得到的是

temperature,date,locations,weather
42
2017-01-22
"('Berlin', 'Paris')"
sunny
-42
2017-01-22
"('Marseille', 'Moscow')"
cloudy

My code looks like this:我的代码如下所示:

import csv
import datetime

def generate_csv(a_list):
    with open('results.csv', 'w', newline='') as csvfile:
        writer = csv.writer(csvfile, delimiter=',', quotechar='"')
        #writer.writerow(['temperature','date','locations','weather'])
        for i in a_list:
            for j in i:
                print(j[1:])
                writer.writerow(j[1:])
            
test = [(('temperature', 42), ('date', datetime.date(2017, 1, 22)), ('locations', ('Berlin', 'Paris')),  ('weather', 'sunny')),
(('temperature', -42), ('date', datetime.date(2017, 1, 22)), ('locations', ('Marseille', 'Moscow')), ('weather', 'cloudy'))]

generate_csv(test)

The instructions for this example are:此示例的说明是:

Create a function generate_csv(a_list) that will create a csv file called results.csv.

Your function will be called with a list of tuples (like in the following examples). 
The tuples will contains tuples which contains as a first a key and as a second value the value
associated with the key. The keys will always be the same. You must show this keys in 
the first line of your csv. After this line you need to add the values formatted like this :

a list or a tuple must be string: "a,b,c"
a date must follow the US Standard: "month/day/year"
You don't need to format the other values.

Your csv must use ',' as separator and '"' as quotechar.

How can I get rid of the newline between each line I write?我怎样才能摆脱我写的每一行之间的换行符? What is the best way to format the tuples and the datetime so it matches the requested output?格式化元组和日期时间以使其匹配请求的 output 的最佳方法是什么? If I convert the output to str like this:如果我像这样将 output 转换为 str :

writer.writerow(str(j[1:]))

The output is a mess and becomes this: output 一团糟,变成了这样:

(,4,2,",",)
(,d,a,t,e,t,i,m,e,.,d,a,t,e,(,2,0,1,7,",", ,1,",", ,2,2,),",",)
(,(,',B,e,r,l,i,n,',",", ,',P,a,r,i,s,',),",",)
(,',s,u,n,n,y,',",",)
(,-,4,2,",",)
(,d,a,t,e,t,i,m,e,.,d,a,t,e,(,2,0,1,7,",", ,1,",", ,2,2,),",",)
(,(,',M,a,r,s,e,i,l,l,e,',",", ,',M,o,s,c,o,w,',),",",)
(,',c,l,o,u,d,y,',",",)

You need to create a dictionary out of the nested tuples by using map您需要使用map从嵌套元组中创建一个字典

import csv

test = list(map(dict, test))
keys = test[0].keys()
with open('result.csv', 'w', newline='') as op:
    dict_writer = csv.DictWriter(op, keys)
    dict_writer.writeheader()
    dict_writer.writerows(test)

An alternative using pandas package if you have a lot of data and multiple manipulations on the columns.如果您有大量数据和对列进行多次操作,则可以使用pandas package 的替代方法。

import pandas as pd

df = pd.DataFrame(map(dict, test))
df.to_csv('result.csv')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM