【问题标题】:How to use if elif and else in python to perform an action to create a new json file every month, on the first day of each month?如何在 python 中使用 if elif 和 else 在每个月的第一天执行一个操作以创建一个新的 json 文件?
【发布时间】:2020-07-07 20:07:18
【问题描述】:

我有一个 python 脚本,它在一年中的每一天和每个月每分钟存储一行数据。但是由于每天存储的数据量很大,所以这个json文件最终每年有518400行数据,大小为67MB。

我需要编写一个脚本来执行一个动作以在每年每个月的第一天创建一个新的 json 文件,因此,它不会将当年的所有数据累积在一个文件中,这将导致一月、二月、三月……十二月的 json 文件。

我的第一个想法是在python中使用if elif和else,但我不知道该怎么做。

有人知道我该怎么做吗?

这是我的json文件的格式:i.imgur.com/jDzhWRI.png

【问题讨论】:

  • 如果您的脚本将一行附加到 JSON 文件,那么它是有效的 JSON 吗?
  • 我在您的解释中没有看到您使用了“如果”这个词。那你为什么认为你的代码中需要if-elif
  • 你可以看看 logrotate 之类的东西
  • @gabriel-cassol 尝试询问特定的代码相关问题。所以。不一定是讨论论坛,而是代码 sn-ps 和错误。 stackoverflow.com/help/how-to-ask
  • 这是我的json文件格式:i.imgur.com/jDzhWRI.png

标签: python json if-statement io


【解决方案1】:

您可以执行以下操作:

从您的日期中提取年份和月份,并使用yyyy_mm 后缀命名您的文件:

import datetime
dt = datetime.datetime.today()
filename = f"my_file_{dt.year}_{dt_month}"

然后将你的数据写入指定文件:

with open(filename,'a+') as f: 
    # the data will be appended to the file if it exists and if not, the 
    # file will be created
    f.write(data)

【讨论】:

    猜你喜欢
    • 2021-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多