繁体   English   中英

如何在python中使用if elif和else在每个月的第一天执行一个动作来创建一个新的json文件?

[英]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 脚本,它在一年中的每一天和每个月每分钟存储一行数据。 但是,由于每天存储的数据太多,json文件最终每年有518,400行数据,大小为67MB。

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

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

有谁知道我怎么能做到这一点?

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

您可以执行以下操作:

从您的日期中提取年份和月份,并使用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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM