用.write()Python 3编写变量

时间:2014-07-28 19:05:59

标签: python

我正在尝试使用Python将字符串+ datetime写入文本文件。我试图制作一个基本的记录器,它将以一种格式记录日期时间; "完整工作日,日期编号,完整月份名称,全年,12小时格式,分钟,秒,上午/下午,UTC"。我读到file.write()只能接受字符串而不是整数或日期等。那么我怎样才能将这项工作写入文本文件?

grab_date = datetime.datetime.now().strftime("%A %d, %B %Y %I:%M:%S %p %Z")
firstline = "Log Created: ", grab_date, "/nLog deleted and recreated."
f = open("gen-log.txt", "w")
f.seek(0)
f.write(firstline)
f.close()
编辑:不太确定为什么,但我在一篇文章中读到f.seek(0)做了一些事情并且它对他们有效。大声笑。我把它留在那里。遗憾。

1 个答案:

答案 0 :(得分:1)

您可以将数据格式化为字符串;使用string formatting,例如:

firstline = "Log Created: {}/nLog deleted and recreated.".format(grab_date)

您还可以利用print()将所有参数转换为字符串和自动换行的功能,并让 it 写入该文件:

print("Log Created:", grab_date, file=f)
print("Log deleted and recreated.", file=f)

如果可以避免,请不要重新发明测井轮并使用logging module。它可以是configured to take a different date format

>>> import logging
>>> logging.basicConfig(datefmt="%A %d, %B %Y %I:%M:%S %p %Z", format='Log Created: %(asctime)-15s %(message)s')
>>> logging.warn('Foo bar baz!')
Log Created: Monday 28, July 2014 08:13:44 PM BST Foo bar baz!
相关问题