python新建以时间命名的目录

 2023-09-10 阅读 27 评论 0

摘要:1.新建三级目录,第一级是去年的年份,第二级是去年的月,第三级为去年的日,在日的文件中写入今年的时分秒 import os import time import shutil def create_file(path):gettime=time.localtime() #获得当前时间的列表getyear=gettime.tm_

1.新建三级目录,第一级是去年的年份,第二级是去年的月,第三级为去年的日,在日的文件中写入今年的时分秒

import os
import time
import shutil
def create_file(path):gettime=time.localtime()  #获得当前时间的列表getyear=gettime.tm_year-1  #获取去年的时间getmon=gettime.tm_mon-1  #获得去年月
  getday=gettime.tm_mday-1 #获得去年的日if getmon==0: #如果为0就重置getmon=12setpath=path+str(getyear)setpath2=setpath+"\\"+str(getmon)+"\\"+str(getday)print setpath2try:if(os.path.exists(setpath)):print u"文件已存在" # 目前删除目录还有问题, # print u"子目录",filelist# os.removedirs(setpath2); 空目录删除成功 filelist=os.listdir(setpath2)print "filelist",filelist for i in filelist:filepath=os.path.join(setpath2,i)print u"filepath",filepath if os.path.isfile(setpath2):# os.remove(filepath)os.removedirs(setpath2)#空目录删除成功elif os.path.isdir(filepath):print "5"os.rmdir(filepath)#shutil.rmtree(filepath,True)#好凶残,直接弹框提示,删除也是成功的'''for root,dirs,files in os.walk(filepath):for name in dirs:os.rmdir(os.path.join(root,name))print "2"for name in files:os.remove(os.path.join(root,name))print "3"#print u"文件已存在,已执行删除"'''else:os.mkdir(path+str(getyear)) os.chdir(path+str(getyear))os.mkdir(str(getmon))os.chdir(str(getmon))os.mkdir(str(getday))os.chdir(str(getday))filename=time.strftime('%H-%M-%S',time.localtime(time.time()))+".txt"with open(filename,"w") as fp:content=u"今天是今年的第 %s 天,今年的第 %s 个星期" %(gettime.tm_yday,time.strftime("%U",gettime)) #格式输出fp.write(content.encode("utf-8"))except Exception,e:print ecreate_file("D:\\")

主要是时间函数 import time的使用

python中函数名的命名规则?

 

转载于:https://www.cnblogs.com/chongyou/p/6279354.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/2/37486.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息