可以选择文件修改单个文件的时间(建立、修改、访问时间),也可以修改一个目录下所有文件的时间。可以生成随机时间偏移量。
代码如下:
from win32file import CreateFile, SetFileTime, GetFileTime, CloseHandle
from win32file import GENERIC_READ, GENERIC_WRITE, OPEN_EXISTING
from pywintypes import Time
import time
import os
import random
def modifyFileTime(filePath, createTime, modifyTime, accessTime, offset):
"""
用来修改任意文件的相关时间属性,时间格式:YYYY-MM-DD HH:MM:SS
:param filePath: 文件路径名
:param createTime: 创建时间
:param modifyTime: 修改时间
:param accessTime: 访问时间
:param offset: 时间偏移的秒数,tuple格式,顺序和参数时间对应
"""
try:
format = "%Y-%m-%d %H:%M:%S" # 时间格式
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)
def modifyAllTime(path,cTime, mTime, aTime):
#遍历文件和文件夹
for root, dirs, files in os.walk(path):
# root 当前正在访问的文件夹路径
# dirs 该文件夹下的子目录名list(不包括子子目录)
# files 表示该文件夹下的文件list
# 遍历文件
for f in files:
fname=os.path.join(root, f)
offset=[0,0,0]#秒数偏移量
# offset[0]=random.randint(0, 59)
# offset[1] = random.randint(0, 59)
# offset[2] = random.randint(0, 59)
print(os.path.join(root, fname))
if modifyFileTime(fname, cTime, mTime, aTime, offset)==0:
print(' 完成')
else:
print(' 失败')
# # 遍历所有的文件夹
# for d in dirs:
# print(os.path.join(root, d))
# 调用
cTime = "2020-06-31 19:36:00" # 创建时间
mTime = "2020-06-31 19:36:00" # 修改时间
aTime = "2020-06-31 19:36:00" # 访问时间
#修改单个文件--------------------------
# fName = r"D:\我的文档\..."
# offset = (0, 1, 2) # 偏移的秒数
# r = modifyFileTime(fName, cTime, mTime, aTime, offset)
# if r == 0: print('修改完成')
# if r == 1: print('修改失败')
#修改整个文件--------------------------
path = r"D:\我的文档\..."
modifyAllTime(path, cTime, mTime, aTime)
其他python 文件操作:
https://blog.csdn.net/lanshi00/article/details/106493816
修改文件(修改、访问时间):