2016-06-09 94 views
0

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

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

使用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)是创建作家sufficent。 Excel的默认值是正确的。

+0

我实现了这个。现在它在第一列的每一行打印一个字符。 –

+0

@DigantaBharali啊,'row'是一串数据。如果该行已经是以逗号分隔的格式,则不需要'csv.writer'。你可以'c.writerow(row.split(','))',虽然。我会更新。 –

+0

我重新写了那部分...作品 –