簡體   English   中英

將解壓元組列表寫入 CSV

[英]Writing a list of unpacked tuples to CSV

我正在嘗試將元組列表(不平坦)寫入 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'))]

和 output 應該是

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.

我怎樣才能擺脫我寫的每一行之間的換行符? 格式化元組和日期時間以使其匹配請求的 output 的最佳方法是什么? 如果我像這樣將 output 轉換為 str :

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

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

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