【问题标题】:How to automate writing filename from a given while saving data as csv?如何在将数据保存为 csv 时自动从给定写入文件名?
【发布时间】:2020-07-09 09:38:36
【问题描述】:

我正在使用pytrends API 收集谷歌趋势数据并保存到 csv 文件中。如何通过从列表中获取名称来自动写入文件名?

我尝试了以下方法,但它给了我generator object 而不是ray ban or abaco

我的代码:


user_kw_list = ['ray ban','abaco sunglasses']

interest_over_time_df.to_csv("./data/{}_interest_over_time.csv".format(user_kw_list[i] for i in range(len(user_kw_list))), index=True)

【问题讨论】:

    标签: python csv format list-comprehension format-string


    【解决方案1】:

    这取决于您是想要一个包含整个 user_kw_list 的长文件名,还是要为列表中的每个关键字保存一个文件。

    无论哪种情况,f-strings 都值得研究。如果你的 Python 版本支持的话,相比 format 方法,它非常简洁,并且优化得很好。阅读更多关于 f-strings here.

    如果你想要一个长文件名,你需要join这些项目一起。在这种情况下,您几乎可以肯定不需要列表推导。这是一种可能的解决方案:

    user_kw_list = ['ray ban','abaco sunglasses']
    
    joined = ('_or_').join(user_kw_list).replace(' ', '_')
    # .replace(' ', '_') is optional. It maintains the snake_case naming convention.
    
    path = f"./data/{joined}_interest_over_time.csv"
    # This is functionally similar to: "./data/{}_interest_over_time.csv".format(joined)
    
    interest_over_time_df.to_csv(path, index=True)
    # This will save the file as ./data/ray_ban_or_abaco_sunglasses_interest_over_time.csv
    # Note: Very long filenames can sometimes cause problems on some operating systems.
    

    相反,如果您想为列表中的每个关键字保存一个文件,问题是您的循环包含在方法调用中。应该反过来,for 循环封装了to_csv 方法。

    对于这个用例,传统的 for 循环可能更具可读性,因为您正在运行带有副作用的代码,而不是返回一个变量。

    一个解决方案如下所示:

    user_kw_list = ['ray ban','abaco sunglasses']
    
    for kw in user_kw_list:
        kw = kw.replace(' ', '_') 
        # As before, this line is optional. It maintains the snake_case convention.
        
        path = f"./data/{kw}_interest_over_time.csv"
        # This is functionally similar to: "./data/{}_interest_over_time.csv".format(kw)
    
        interest_over_time_df.to_csv(path, index=True)
        # This will save two files: ray_ban_interest_over_time.csv 
        # and abaco_sunglasses_interest_over_time.csv
    

    如果第二种情况需要是列表推导式,则如下所示:

    [interest_over_time_df.to_csv(f"./data/{kw}_interest_over_time.csv", index=True) for kw in user_kw_list]
    

    【讨论】:

    • 已更新以解决原始问题中先前未被注意到的歧义。
    猜你喜欢
    • 2021-12-06
    • 2018-09-30
    • 2015-06-03
    • 1970-01-01
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多