您好,登錄后才能下訂單哦!
突如其來(lái)想知道一下 python 如何修改文件的屬性(創(chuàng)建、修改、訪問(wèn)時(shí)間),于是就去網(wǎng)上搜集了可行方案,也就有了這篇博客
方案一
from win32file import CreateFile, SetFileTime, GetFileTime, CloseHandle from win32file import GENERIC_READ, GENERIC_WRITE, OPEN_EXISTING from pywintypes import Time # 可以忽視這個(gè) Time 報(bào)錯(cuò)(運(yùn)行程序還是沒(méi)問(wèn)題的) import time def modifyFileTime(filePath, createTime, modifyTime, accessTime, offset): """ 用來(lái)修改任意文件的相關(guān)時(shí)間屬性,時(shí)間格式:YYYY-MM-DD HH:MM:SS 例如:2019-02-02 00:01:02 :param filePath: 文件路徑名 :param createTime: 創(chuàng)建時(shí)間 :param modifyTime: 修改時(shí)間 :param accessTime: 訪問(wèn)時(shí)間 :param offset: 時(shí)間偏移的秒數(shù),tuple格式,順序和參數(shù)時(shí)間對(duì)應(yīng) """ try: format = "%Y-%m-%d %H:%M:%S" # 時(shí)間格式 cTime_t = timeOffsetAndStruct(createTime, format, offset[0]) mTime_t = timeOffsetAndStruct(modifyTime, format, offset[1]) aTime_t = timeOffsetAndStruct(accessTime, format, offset[2]) fh = CreateFile(filePath, GENERIC_READ | GENERIC_WRITE, 0, None, OPEN_EXISTING, 0, 0) createTimes, accessTimes, modifyTimes = GetFileTime(fh) createTimes = Time(time.mktime(cTime_t)) accessTimes = Time(time.mktime(aTime_t)) modifyTimes = Time(time.mktime(mTime_t)) SetFileTime(fh, createTimes, accessTimes, modifyTimes) CloseHandle(fh) return 0 except: return 1 def timeOffsetAndStruct(times, format, offset): return time.localtime(time.mktime(time.strptime(times, format)) + offset) if __name__ == '__main__': # 需要自己配置 cTime = "2019-12-13 21:51:02" # 創(chuàng)建時(shí)間 mTime = "2019-02-02 00:01:03" # 修改時(shí)間 aTime = "2019-02-02 00:01:04" # 訪問(wèn)時(shí)間 fName = r"E:\test_pro\fileOperate\test.xlsx" # 文件路徑,文件存在才能成功(可以寫(xiě)絕對(duì)路徑,也可以寫(xiě)相對(duì)路徑) offset = (0, 1, 2) # 偏移的秒數(shù)(不知道干啥的) # 調(diào)用函數(shù)修改文件創(chuàng)建時(shí)間,并判斷是否修改成功 r = modifyFileTime(fName, cTime, mTime, aTime, offset) if r == 0: print('修改完成') elif r == 1: print('修改失敗')
方案二(無(wú)法修改文件創(chuàng)建時(shí)間)
可以去這里http://tools.jb51.net/code/unixtime/轉(zhuǎn)換時(shí)間,也可以自己處理時(shí)間戳與格式化時(shí)間
import os file_path = "pip.txt" print(os.stat(file_path)) # os.stat_result( # st_mode=33206, # st_ino=2251799813766228, # st_dev=3050226722, # st_nlink=1, # st_uid=0, # st_gid=0, # st_size=851, # st_atime=1576241919, # st_mtime=1574385498, # st_ctime=1576241919, # ) # 只能修改 訪問(wèn)時(shí)間 與 修改時(shí)間(暫不知道怎么修改創(chuàng)建時(shí)間) os.utime(file_path, (1576335480, 1576335480)) print(os.stat(file_path)) # os.stat_result( # st_mode=33206, # st_ino=2251799813766228, # st_dev=3050226722, # st_nlink=1, # st_uid=0, # st_gid=0, # st_size=851, # st_atime=1576335480, # st_mtime=1576335480, # st_ctime=1576241919, # )
以上就是python 兩種方法修改文件的創(chuàng)建時(shí)間、修改時(shí)間、訪問(wèn)時(shí)間的詳細(xì)內(nèi)容,更多關(guān)于python 修改文件的資料請(qǐng)關(guān)注億速云其它相關(guān)文章!
免責(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)容。