Python檔案時間操作步驟程式碼詳解
阿新 • • 發佈:2020-04-14
一 按時間建立檔案
原始碼
# 截圖方式二 # coding=utf-8 import os import time # 當前年月日時分秒時間 2020-01-16-10_11_49 picture_time = time.strftime("%Y-%m-%d-%H_%M_%S",time.localtime(time.time())) #當前年月日 2020-01-16 directory_time = time.strftime("%Y-%m-%d",time.localtime(time.time())) print('當前年月日時分秒時間:'+ picture_time) print("當前年月日:"+directory_time) # 獲取當前檔案目錄 print('當前檔案目錄:'+os.getcwd()) # 獲取到當前檔案的目錄,並檢查是否有 directory_time 資料夾,如果不存在則自動新建 directory_time 檔案 try: File_Path = os.getcwd() + '\\' + directory_time + '\\' print(os.path) #exists判斷檔案路徑是否存在 if not os.path.exists(File_Path): os.makedirs(File_Path) print("目錄新建成功:%s" % File_Path) else: print("目錄已存在!!!") except BaseException as msg: print("新建目錄失敗:%s" % msg) #切換目錄 os.chdir("D:/git") print('切換後的目錄位置:'+os.getcwd())
原始碼執行控制檯列印:
當前年月日時分秒時間:2020-01-16-11_19_12
當前年月日:2020-01-16
當前檔案目錄:D:\git\gongcheng
<module 'ntpath' from 'D:\Python36\lib\ntpath.py'>
目錄新建成功:D:\git\gongcheng\2020-01-16
切換後的目錄位置:D:\git
二 獲取環境變數、程序、父程序
原始碼
import os #獲取系統環境變數 print("環境變數是:"+os.environ["CLASSPATH"]) #獲取當前程序ID print(os.getpid()) #獲取父程序ID print(os.getppid())
原始碼執行控制檯列印:
環境變數是:.;C:\Program Files\Java\jdk1.8.0_101\lib\dt.jar;C:\Program >Files\Java\jdk1.8.0_101\lib\tools.jar;
10760
11224
三、獲取當前檔案的建立、修改、訪問時間
原始碼
import time import os filepath = 'D:\gongcheng' #獲取檔案的建立時間 get create time ctime = os.path.getctime(filepath) print("建立時間是:"+time.ctime(ctime)) #獲取檔案的修改時間 get modify time utime = os.path.getmtime(filepath) print("修改時間是:"+time.ctime(utime)) #獲取檔案的訪問時間 get active time atime = os.path.getatime(filepath) print("訪問時間是:"+time.ctime(atime))
原始碼執行控制檯列印:
建立時間是:Fri Jul 5 19:13:27 2019
修改時間是:Mon Jan 13 18:27:26 2020
訪問時間是:Mon Jan 13 18:27:26 2020
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。