Python CSV输出

时间:2016-06-09 18:18:14

标签: python-2.7 python-3.x csv web-crawler export-to-csv

我有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)

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

我想要的输出是:    enter image description here

1 个答案:

答案 0 :(得分:1)

使用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的默认值是正确的。