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

How am I able to create a file structure based on the current date?



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

我已经尝试过使用 datetime 包手动编辑文件名。

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 在 ..
[Errno 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))