I would like to prevent unnecessary commas from entering the CSV output of the list in python.

Asked 2 years ago, Updated 2 years ago, 88 views

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!

python csv google-analytics-api

2022-09-30 20:50

1 Answers

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


2022-09-30 20:50

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.