I want to get a number from the GA reporting API and output it in CSV.
I wrote the following functions in Python.
""Function to aggregate from GA""
default_results(service,profile_id):
# Use the Analytics Service Object to query the Core Reporting API
# For the number of sessions with the past seven days.
return service.data().ga().get(
id='ga:'+profile_id,
start_date = '7 daysAgo',
end_date = 'today',
dimensions='ga:date',
metrics='ga:sessions').execute()
"""Function to display aggregated results"""
defaultprint_data_table(results):
output = [ ]
for header in results.get('columnHeaders'):
output.append('%s'%header.get('name')))
if results.get('rows', [ ]):
for row in results.get('rows'):
output.append('%s'%row)
print(output)
f = open ('output.csv', 'wt')
Writer=csv.writer(f, lineterminator='\n')
Writer.writerows (output)
f.close()
If you use the above function to get a number,
g, a, :, d, a, t, e
g, a, :, s, e, s, s, i, o, n, s
[,',2,0,1,5,0,6,0,5,',",", ,',1,',]
[,',2,0,1,5,0,6,0,6,',",", ,',2,',]
[,',2,0,1,5,0,6,0,7,',",", ,',3,',]
[,',2,0,1,5,0,6,0,8,',",", ,',4,',]
[,',2,0,1,5,0,6,0,9,',",", ,',5,',]
[,',2,0,1,5,0,6,1,0,',",", ,',6,',]
[,',2,0,1,5,0,6,1,1,',",", ,',7,',]
[,',2,0,1,5,0,6,1,2,',",", ,',8,',]
The output is like this and contains unnecessary commas.
I looked at the specification of Python's csv module.
I don't know how to get a comma.
Could you tell me the solution?
Thank you for your cooperation!
If you look backwards from the results, the get_results
values should have been as follows:
{
"columnHeaders":[
{"name":"ga:date"},
{"name":"ga:sessions"}
],
"rows": [
["20150605", "1"],
["20150606", "2"],
["20150607", "3"],
["20150608", "4"],
["20150609", "5"],
["20150610", "6"],
["20150611", "7"],
["20150612", "8"]
]
}
If so, it will work if you write like this
def print_data_table(results):
header = [h.get('name') for h in results.get('columnHeaders')]
output = [header] + results.get('rows', [])
print(output)
with open('output.csv', 'wt') as f:
writer=csv.writer(f, lineterminator='\n')
writer.writerows (output)
CSV Contents
ga:date, ga:sessions
20150605,1
20150606,2
20150607,3
20150608,4
20150609,5
20150610,6
20150611,7
20150612,8
618 Uncaught (inpromise) Error on Electron: An object could not be cloned
578 Understanding How to Configure Google API Key
915 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
612 GDB gets version error when attempting to debug with the Presense SDK (IDE)
© 2024 OneMinuteCode. All rights reserved.