Python腳本按照當前日期創(chuàng)建多級目錄
更新時間:2019年03月01日 09:21:42 作者:我是李超人
今天小編就為大家分享一篇關于Python腳本按照當前日期創(chuàng)建多級目錄,小編覺得內容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
使用python腳本按照年月日生成多級目錄,創(chuàng)建的目錄可以將系統(tǒng)生成的日志文件放入其中,方便查閱,代碼如下:
#!/usr/bin/env python
#coding=utf-8
import time
import 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/'+year
fileMonth=fileYear+'/'+month
fileDay=fileMonth+'/'+day
if 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
進入文件夾下,可以看到文件目錄已經存在了
[root@localhost 22]# pwd /data/python-scripts/inspector/AccountInspector/badJsidAccountLogs/2017/01/22
文件也已經生成
[root@localhost 22]# ll total 4 -rw-r--r--. 1 root root 29 Jan 22 10:20 timeFile_0122102052.txt
文件內容
localtime=2017-01-22 10:20:52
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內容請查看下面相關鏈接
您可能感興趣的文章:
相關文章
Python中的?Numpy?數(shù)組形狀改變及索引切片
這篇文章主要介紹了Python中的?Numpy?數(shù)組形狀改變及索引切片,Numpy提供了一個reshape()方法,它可以改變數(shù)組的形狀,返回一個新的數(shù)組,更多相關內容需要的小伙伴可以參考下面文章2022-05-05

