使用python腳本按照年月日生成多級目錄,創(chuàng)建的目錄可以將系統(tǒng)生成的日志文件放入其中,方便查閱,代碼如下:
#!/usr/bin/env python#coding=utf-8import timeimport os.path#獲得當前系統(tǒng)時間的字符串localtime=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))print('localtime='+localtime)#系統(tǒng)當前時間年份year=time.strftime('%Y',time.localtime(time.time()))#月份month=time.strftime('%m',time.localtime(time.time()))#日期day=time.strftime('%d',time.localtime(time.time()))#具體時間 小時分鐘毫秒mdhms=time.strftime('%m%d%H%M%S',time.localtime(time.time()))fileYear='/data/python-scripts/inspector/AccountInspector/badJsidAccountLogs/'+yearfileMonth=fileYear+'/'+monthfileDay=fileMonth+'/'+dayif not os.path.exists(fileYear):  os.mkdir(fileYear)  os.mkdir(fileMonth)  os.mkdir(fileDay)else:  if not os.path.exists(fileMonth):    os.mkdir(fileMonth)    os.mkdir(fileDay)  else:    if not os.path.exists(fileDay):      os.mkdir(fileDay)#創(chuàng)建一個文件,以‘timeFile_'+具體時間為文件名稱fileDir=fileDay+'/timeFile_'+mdhms+'.txt'out=open(fileDir,'w')#在該文件中寫入當前系統(tǒng)時間字符串out.write('localtime='+localtime)out.close()執(zhí)行
[root@localhost AccountInspector]# python timeFile.py localtime=2017-01-22 10:20:52
進入文件夾下,可以看到文件目錄已經(jīng)存在了
[root@localhost 22]# pwd/data/python-scripts/inspector/AccountInspector/badJsidAccountLogs/2017/01/22
文件也已經(jīng)生成
[root@localhost 22]# lltotal 4-rw-r--r--. 1 root root 29 Jan 22 10:20 timeFile_0122102052.txt
文件內(nèi)容
localtime=2017-01-22 10:20:52
總結
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對武林站長站的支持。如果你想了解更多相關內(nèi)容請查看下面相關鏈接
新聞熱點
疑難解答