将解压后的元组列表写入 CSV

时间:2021-05-09 06:12:19

标签: python csv tuples

我正在尝试将元组列表(不是平面的)写入 CSV。 例如,输入将是:

[(('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'))]

和输出应该是

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

但是我得到的是

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

我的代码如下:

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)

这个例子的说明是:

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.

如何去掉我写的每一行之间的换行符? 格式化元组和日期时间以使其与请求的输出匹配的最佳方法是什么? 如果我像这样将输出转换为 str :

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

输出一团糟,变成这样:

(,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,',",",)

1 个答案:

答案 0 :(得分:1)

您需要使用 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)

如果您有大量数据和对列的多次操作,则使用 pandas 包的替代方法。

import pandas as pd

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