python将函数结果存储到文件

python将函数结果存储到文件,python,file,save,store,Python,File,Save,Store,我有一个函数(见下文),可以从谷歌分析中获取数据到我的电脑。 我想将结果存储在csv文件中,但我不知道如何存储。请帮帮我。 我可以在屏幕上打印结果,但无法保存 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(

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

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)

用这个替换退货

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

您应该在名为output.txt的文件中获得与givs NameError相同的打印输出:名称“query”未定义def print_top_pages(服务、站点、开始日期、结束日期、最大结果=10000):“打印出给定站点的前X页。s”“query=service.data().ga()。get(ids=site,start\u date=start,end\u date=end,dimensions='ga:dimension20,ga:date',metrics='ga:session,ga:sessionDuration',sort='-ga:pageviews',filters='ga:hostname!=localhost',samplingLevel='HIGHER\u PRECISION',max\u results=max\u results)。打开(“output.txt”,“w”)执行()as out:out.write(打印数据表(查询))