python文件目录不存在时,自动生成

 1 #!/usr/bin/python
 2 # _*_coding:utf-8_*_
 3 import os
 4 import datetime
 5 
 6 def getDirName():
 7     # 年-月-日 时:分:秒
 8     now_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
 9     #
10     year_time =datetime.datetime.now().strftime('%Y')
11     # 年-月
12     month_time = datetime.datetime.now().strftime('%Y-%m')
13     # 年-月-日
14     daytime = datetime.datetime.now().strftime('%Y-%m-%d')
15     # 时:分:秒
16     hourtime = datetime.datetime.now().strftime("%H:%M:%S")
17     print(now_time + "\n"+daytime + "\n" + hourtime)
18 
19     #得到当前工作目录,即当前Python脚本工作的目录路径: os.getcwd()
20     pwd = os.getcwd()+"\\"+year_time+"\\"+month_time+"\\"+daytime
21     # print(pwd)
22     # 文件路径
23     word_name = os.path.exists(pwd)
24     # 判断文件是否存在:不存在创建
25     if not word_name:
26         os.makedirs(pwd)
27         result={"status":1,"msg":"文件目录不存在,已自动生成!"}
28     else:
29         result = {"status": 0, "msg": "文件已存在!"}
30     return result
31 if __name__ == '__main__':
32     tt=getDirName()
33     print(tt)

猜你喜欢

转载自www.cnblogs.com/xh0203/p/12652411.html