0

I have piwik response data. I need to output it to csv file. And when i open it, it should be properly formatted in Excel. What i am getting now is a comma separated file in excel and i have to format it every time. Below is my code

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)

If i use the last two commented lines, it gives me in the proper format but one character in each cell. The output i am getting is: enter image description here

And the output i want is: enter image description here

1 Answer 1

1

Use c.writerow(row.split(',')) not c.writerow([row]). The second is writing the entire row in one column. writerow takes an iterable of the column values. Since row is a string, c.writerow(row) would iterate over the single characters of the string, so split on comma to get the right kind of list.

Also for writing csv files, use (per csv documentation):

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

c = csv.writer(fp) is sufficent for creating the writer. The defaults are correct for Excel.

Sign up to request clarification or add additional context in comments.

2 Comments

I implemented this. Now it prints one character in each row f the first column.
@DigantaBharali Ah, row is a single string of data. You don't really need csv.writer if the line is already in a comma-delimited format. You can c.writerow(row.split(',')), though. I'll update.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.