python - 将输出导出到文件,每个日期递增文件名
问题描述
什么是我可以在 Python 中使用的命令,而不使用命令行,而不是打印程序的输出,而是将其发送到文件中?另外,如果文件是每天命名的(2019-03-11)(不一定是今天的日期),我如何增加文件的名称?
解决方案
在整个代码执行过程中,日期如何变化?
如果它只是从您的数据集中获取日期,您的代码应该如下所示:
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')
我希望这就是你要找的。
推荐阅读
- c++ - 如何在 C++ 中重载后缀运算符?
- python - 如何在 python 中使用 pyfirmata 访问超声波传感器
- php - 向类构造函数添加回调闭包
- android - Where can you get this scrollable/expandable bar View/Resrouce?
- python-3.x - pylint 已安装,但在带有 zsh 的 macOS Catalina 上找不到
- pyqt - 如何设置单独存储在列表中的小部件的样式表
- r - 创建一个确定异常值影响的函数
- python - 在哪里放置 db.close 以关闭 python 脚本中函数内部的 mysql 连接
- sql - Oracle:需要在 CREATE OR REPLACE FORCE EDITIONABLE VIEW 之后提交
- sql - 用 SQL 中的默认值替换空白值