溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python腳本按照當(dāng)前日期如何創(chuàng)建多級(jí)目錄

發(fā)布時(shí)間:2021-07-12 10:24:07 來(lái)源:億速云 閱讀:161 作者:小新 欄目:開(kāi)發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)Python腳本按照當(dāng)前日期如何創(chuàng)建多級(jí)目錄,小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

使用python腳本按照年月日生成多級(jí)目錄,創(chuàng)建的目錄可以將系統(tǒng)生成的日志文件放入其中,方便查閱,代碼如下:

#!/usr/bin/env python
#coding=utf-8
import time
import os.path
#獲得當(dāng)前系統(tǒng)時(shí)間的字符串
localtime=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
print('localtime='+localtime)
#系統(tǒng)當(dāng)前時(shí)間年份
year=time.strftime('%Y',time.localtime(time.time()))
#月份
month=time.strftime('%m',time.localtime(time.time()))
#日期
day=time.strftime('%d',time.localtime(time.time()))
#具體時(shí)間 小時(shí)分鐘毫秒
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)建一個(gè)文件,以‘timeFile_'+具體時(shí)間為文件名稱(chēng)
fileDir=fileDay+'/timeFile_'+mdhms+'.txt'
out=open(fileDir,'w')
#在該文件中寫(xiě)入當(dāng)前系統(tǒng)時(shí)間字符串
out.write('localtime='+localtime)
out.close()

執(zhí)行

[root@localhost AccountInspector]# python timeFile.py 
localtime=2017-01-22 10:20:52

進(jìn)入文件夾下,可以看到文件目錄已經(jīng)存在了

[root@localhost 22]# pwd
/data/python-scripts/inspector/AccountInspector/badJsidAccountLogs/2017/01/22

文件也已經(jīng)生成

[root@localhost 22]# ll
total 4
-rw-r--r--. 1 root root 29 Jan 22 10:20 timeFile_0122102052.txt

文件內(nèi)容

localtime=2017-01-22 10:20:52

關(guān)于“Python腳本按照當(dāng)前日期如何創(chuàng)建多級(jí)目錄”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI