python根据日期创建目录结构 [英] python create directory structure based on the date

查看:37
本文介绍了python根据日期创建目录结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下函数根据今天的日期创建目录,

I used the following function to created dirctory based on today date ,

#!/usr/bin/python
import time, datetime, os

today = datetime.date.today()  

todaystr = today.isoformat()   

os.mkdir(todaystr)

所以输出将是

/2015-12-22/

我正在寻找的是调整结构,即根据日期创建目录结构如下

what i'm looking to is adjust the structure which is create dirctories structure based on day date as following

/2015/12/22
/2015/12/23
etc 

每当我运行该函数时,它都会检查日期并确保文件夹存在,否则会创建它..有什么要遵循的提示吗?

when ever i run the function it will check the date and make sure the folder is exist other wise will create it .. any tips to follow here ?

推荐答案

考虑使用 strftime 代替.您可以使用它来定义您喜欢的格式.您还需要使用 os.makedirs,如下面的 @Valijon 所述.

Consider using strftime instead. Which you can use to defined a format to your liking. You will also need to use os.makedirs as described by @Valijon below.

os.makedirs(time.strftime("/%Y/%m/%d"), exist_ok=True)

您还可以附加给定时间以创建过去或未来的时间戳.

You can also append a given time to create a time-stamp in the past or in the future.

time.strftime("/%Y/%m/%d", time.gmtime(time.time()-3600)) # -1 hour

还要注意你的路径有点危险,除非你想直接在根分区下创建文件夹.

Also note that your path is a bit dangerous, unless you want to create folders directly under the root partition.

请注意,如果目录已经存在,makedirs 将在默认情况下引发异常,您可以指定 exist_ok=True 来避免这种情况,在文档中阅读更多相关信息os.makedirs.

Note that makedirs will raise an exception by default if the directory already exists, you can specify exist_ok=True to avoid this, read more about it in the docs for os.makedirs.

自 Python 3.4 起,引入了 pathlib 模块,它提供了一些目录和文件创建功能.

Since Python 3.4, the module pathlib was Introduced which offers some directory and file creation features.

import time
import pathlib
pathlib.Path(time.strftime("/%Y/%m/%d")).mkdir(parents=True, exist_ok=True)

这篇关于python根据日期创建目录结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆