Python CSV 输出

Python CSV output

我有 piwik 响应数据。我需要将它输出到 csv 文件。当我打开它时,它的格式应该正确 Excel。我现在得到的是 excel 中的逗号分隔文件,我每次都必须对其进行格式化。下面是我的代码

siteIDs = [51]
#def calculate():
for id in siteIDs:
    for date in daterange(min_date, max_date):
        response_data = {}
        #print date.strftime('%Y-%m-%d')
        token_auth = '35a2c1b4707f45cebfbdaa7f6c3af267'
        url = 'http://survey.modul.ac.at/piwikAnalytics/?module=API&method=Live.getLastVisitsDetails&idSite=' + str(id) + '&format=csv&token_auth=' + token_auth + '&period=day&date=' + date.strftime('%Y-%m-%d') + '&filter_limit=2000'
        #print url
        try:
            response=requests.get(url,timeout=100)
            response_url=response.url
            response_data=urllib.urlopen(url)

        except (requests.exceptions.Timeout,requests.exceptions.RequestException,requests.exceptions.HTTPError,requests.exceptions.ConnectionError,socket.error) as e  :
            response_data="error"
        data = response_data.read()
        with open('raw_csv/piwik_'+ str(id) + '_' + date.strftime('%Y-%m-%d')+ '.csv', 'w') as fp:
             c = csv.writer(fp,delimiter=',',lineterminator = '/n')
             #for row in data:
                     #c.writerow([row]) 
             fp.write(data)

如果我使用最后两行注释,它会以正确的格式提供给我,但每个单元格中只有一个字符。 我得到的输出是:

我想要的输出是:

使用 c.writerow(row.split(',')) 而不是 c.writerow([row])。第二种是将整行写在一列中。 writerow 采用可迭代的列值。由于 row 是一个字符串,c.writerow(row) 将遍历字符串的单个字符,因此按逗号拆分以获得正确类型的列表。

对于写入 csv 文件,使用(根据 csv 文档):

open(filename,'wb')           # Python 2.x
open(filename,'w',newline='') # Python 3.x

c = csv.writer(fp) 足以创建编写器。 Excel.

的默认值是正确的