如何根据当前日期创建文件结构?





我正在尝试将CMS中的更改记录到日志文件中。我使用 def logging_on_activity((。我想要的是每天一个新文件,以使日志记录井井有条。

我已经尝试使用日期时间包手动编辑文件名。

def logging_on_activity(platform, appname, msg):
import datetime
now = datetime.datetime.now()
if SITE_TYPE == SiteType.LOCAL:
filename = 'path_to/../logs/' + str(now.__format__('%Y')) + '/' 
+ str(now.__format__('%m')) + '/' 
+ str(now.__format__('%d')) + '/logging.log'
import datetime
date = datetime.date.today().isoformat()
time = datetime.datetime.now().strftime('%H:%m:%S')
# Write to file
with open(filename, 'a') as handle:
handle.write("{0} {1} [ii] [{2:^19}] [{3:^19}]  {4}n".format(date, time, platform, appname, msg))

我得到的错误是:

FileNotFoundError at ..
[错误 2] 没有这样的文件或目录:"itdb_tools/logs/2019/09/11.log">

我想要什么的例子?
日期:2019/09/11 -> 系统正在写入:path_to/../logs/2019/09/11/logging.log
日期:2019/09/12 -> 系统正在写入:path_to/../logs/2019/09/12/logging.log

我希望我想要实现的是可能的。

提前感谢,我希望有人能帮助我朝着正确的方向前进!

您还必须创建每个新目录。所以你必须创建目录 2019、目录 2019/09、目录 2019/09/12、目录 2019/09/11 等。Python open不能只是隐式地动态创建目录。它仅在路径中创建叶注释。

我认为如果您使用os.makedirs(path)创建所需的目录会更容易。 之后,您可以为每个目录创建文件。

import datetime
now = datetime.datetime.now()
pathname = 'your desired directory' + str(now.__format__('%Y')) + '\' + str(now.__format__('%m')) + '\' + str(now.__format__('%d')) + "\"
filename = pathname+ 'logging.log'
import datetime
date = datetime.date.today().isoformat()
time = datetime.datetime.now().strftime('%H:%m:%S')
# Write to file
try:
os.makedirs(pathname)
with open(filename, 'w') as handle:
handle.write("{0} {1} [ii] [{2:^19}] [{3:^19}]  {4}n".format(date, time, platform, appname, msg))
except Exception as e:
with open(filename, 'w') as handle:
handle.write("{0} {1} [ii] [{2:^19}] [{3:^19}]  {4}n".format(date, time, platform, appname, msg))

最新更新