pinkcouture pinkcouture - 1 year ago 135
Python Question

hardcode first column of csv file then import google analytics using Python

Is there a way to hard code the first column of a csv file then import my data from google analytics starting at the second column?

My problem is that when I hardcode the first column then upload my data, my Google analytics data is printing on the 1st column instead of the second column of the csv file.

csv file

def print_csv_file(results):
with open("Google Analytics.csv", "wt") as csvfile:
if results.get('rows', []):
# do headers into output_row
csvfile.write('Site \n')
for i in range(5):
output_row = ""

for header in results.get('columnHeaders'):
output_row += '"' + header.get('name') + '"' + ','

csvfile.write(output_row + '\n')

# do cells into output_row
for row in results.get('rows'):
output_row = ""
counter = 1
for cell in row:
if cell.isdigit():
output_row += cell +','
output_row+= cell +','
except ValueError:
output_row += '"' + cell + '"'+','
counter +=1
csvfile.write(output_row + '\n')
csvfile.write('No Results Found')

def print_top_pages(service, start_date, end_date):
# Print out informat in that's queried.
query =
start_date = start_date,
end_date = end_date,
dimensions = 'ga:year,ga:pagePath',
metrics = 'ga:pageviews,ga:uniquePageviews,ga:avgTimeOnPage,ga:entrances,ga:bounceRate,ga:exitRate',
sort = '-ga:pageviews',
start_index = 1,
max_results = 10000).execute()

Answer Source

When dealing with CSV data, you should use the csv library, which simplify both reading and writing. Since your question is not very clear, I can only guess what you are trying to do. For that, please take a look at this rewrite of your code:

import csv

def print_csv_file(results):
    with open('Google Analytics.csv', 'w') as output_file:
        writer = csv.writer(output_file)

        if 'rows' not in results:
            writer.writerow(['No Results Found'])

        header = ['Site'] + [cell['name'] for cell in results['columnHeaders']]

        for row in results['rows']:
            row.insert(0, 'SiteName')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download