【问题标题】:python store function result to filepython将函数结果存储到文件
【发布时间】:2016-05-23 21:57:22
【问题描述】:

我有一个功能(见下文),可以从 Google 分析中获取数据到我的计算机。 我想将结果存储在 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)

【问题讨论】:

    标签: python file save store


    【解决方案1】:

    用这个替换返回。

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

    您应该在名为 output.txt 的文件中获得相同的打印输出

    【讨论】:

    • 给出 NameError: name 'query' is not defined
    • def print_top_pages(service, site, start_date, end_date, max_results=10000): """打印给定 site.s 的前 X 页""" 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() with open("output.txt", "w") as out: out.write(print_data_table(query ))
    猜你喜欢
    • 2020-01-22
    • 1970-01-01
    • 2012-03-06
    • 1970-01-01
    • 2018-07-11
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 2013-06-30
    相关资源
    最近更新 更多