簡體   English   中英

硬編碼csv文件的第一列,然后使用Python導入谷歌分析

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

有沒有辦法硬編碼csv文件的第一列然后從第二列開始從谷歌分析導入我的數據?

我的問題是,當我對第一列進行硬編碼然后上傳我的數據時,我的Google分析數據將打印在第1列而不是csv文件的第二列。

csv文件

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)

處理CSV數據時,應使用csv庫,這樣可以簡化讀寫操作。 由於你的問題不是很清楚,我只能猜測你想要做什么。 為此,請看一下代碼的重寫:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM