什么是我可以在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')
我希望这就是你要找的东西。
#First create a blank txt file in the directory as your code file. and name it filename.txt. If you want to add to the file add a 'a' mode to the open.
def save():
filename = '2019-01-01.txt'
output = 'Your own output'
file = open(filename, 'w')
file.write(output)
file.close()
import os
os.rename(filename, '2019-01-02.txt')
file = open('file.txt', 'r')
reader = file.read()
print(reader)
file.close()