首页 > 解决方案 > 将输出导出到文件,每个日期递增文件名

问题描述

什么是我可以在 Python 中使用的命令,而不使用命令行,而不是打印程序的输出,而是将其发送到文件中?另外,如果文件是每天命名的(2019-03-11)(不一定是今天的日期),我如何增加文件的名称?

标签: pythonfileexportoutputincrement

解决方案


在整个代码执行过程中,日期如何变化?

如果它只是从您的数据集中获取日期,您的代码应该如下所示:

def toFile(output, date):
    fileName = "{}.txt".format(date)

    with open(fileName, 'w') as file:
        file.write(output)

如果您需要在一段时间内增加(即每隔一天),您将使用上面相同的想法,但使用此代码生成您的日期:

import datetime

#The idea here is to increment our current date by a given number of days (of course, you can change it as you need).

def incrementDate(date, offset):
    #Here, we convert our string date into a datetime object. Then, we add the offset (in days) to our date.

    dateFormat = datetime.datetime.strptime(date, '%Y-%m-%d')
    offsetFormat = datetime.timedelta(days=offset)
    newDate = dateFormat + offsetFormat

    #Finally, we convert it back to string and return.
    return newDate.strftime('%Y-%m-%d')

我希望这就是你要找的。


推荐阅读