pinkcouture pinkcouture - 1 month ago 16
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):
csvfile.write('siteName')
csvfile.write('\n')
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 +','
else:
try:
float(cell)
output_row+= cell +','
except ValueError:
output_row += '"' + cell + '"'+','
counter +=1
csvfile.write(output_row + '\n')
else:
csvfile.write('No Results Found')


def print_top_pages(service, start_date, end_date):
# Print out informat in that's queried.
query = service.data().ga().get(
ids = GA_SITE_CODE,
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()
print_csv_file(query)

Answer

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'])
            return

        header = ['Site'] + [cell['name'] for cell in results['columnHeaders']]
        writer.writerow(header)

        for row in results['rows']:
            row.insert(0, 'SiteName')
            writer.writerow(row)