2016-02-12 74 views
0

我有一个函数(见下文)从Google分析中获取数据到我的电脑。 我想将结果存储在csv文件中,但我不知道如何。请帮助我。 我可以在屏幕上打印结果,但不能将其保存python存储函数结果到文件

def print_top_pages(service, site, start_date, end_date, max_results=10000): 
    """Print out top X pages for a given site.s""" 
    query = service.data().ga().get(
     ids=site, 
     start_date=start, 
     end_date=end, 
     dimensions='ga:dimension20,ga:date', 
     metrics='ga:sessions,ga:sessionDuration', 
     # sort='-ga:pageviews', 
     #filters='ga:hostname!=localhost', 
     samplingLevel='HIGHER_PRECISION', 
     max_results=max_results).execute() 
    return print_data_table(query) 

回答

0

替换此回报。

with open("output.txt", "w") as out: 
    out.write(print_data_table(query)) 

你应该得到一个文件的同一打印输出名为Output.txt

+0

是GIVS NameError:名字 '查询' 没有定义 – Beesure

+0

高清print_top_pages(服务,场地,日期,结束日期,MAX_RESULTS = 10000 ): “”“打印出给定网站的前X页。”“” query = service.data().ga().get( id = site, start_date = start, end_date = end, dimensions ='ga:dimension20,ga:date', metrics ='ga:sessions,ga:sessionDuration', #sort =' - ga:pageviews', #filters ='ga:hostname!= localhost', samplingLevel ='HIGHER_PRECISION', max_results = max_results).execute() with open(“output.txt”,“ w“)如下: out.write(print_data_table(query)) – Beesure

+0

也许你的缩进错了@Beesure? – Forge