[Python] 纯文本查看 复制代码
from win32file import CreateFile, SetFileTime, GetFileTime, CloseHandle
from win32file import GENERIC_READ, GENERIC_WRITE, OPEN_EXISTING
from pywintypes import Time
import time
import os,re
def modifyFileTime(filepath, createTime, modifyTime, accessTime,offset):
"""
用来修改任意文件的相关时间属性,时间格式:20190202000102
"""
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 space2bar(dirname, basename):
newname = basename.replace(' ', '-')
os.rename(os.path.join(dirname, basename), os.path.join(dirname, newname))
return newname
# 获取文件名中的时间用于修改
'''
文件名字格式修改
文件名字格式修改
文件名字格式修改
'''
def get_time(basename):
basename222=basename[4:19]
print(basename222)
basename333=basename222.replace('_','')
return basename333
if __name__ == '__main__':
expression = r"\d{4}-\d{2}-\d{2}" # 文件名格式
'''
文件路径更改
文件路径更改
文件路径更改
'''
dirname = r'D:\天翼云盘下载\Screenshots\ceds'
offset = (0,1,2)
basenames = os.listdir(dirname)
for basename in basenames:
# 去掉文件名中的空格
#if len(basename.split(' ')) > 1:
# basename = space2bar(dirname, basename)
#if re.match(expression, basename):
filepath = dirname+'\\'+basename
# 获取文件名中的时间
temp_time = str(get_time(basename))
#print(temp_time)
#temp_time = '20190202000102'
cTime=mTime=aTime=temp_time
r = modifyFileTime(filepath, cTime, mTime, aTime,offset)
if r == 1:
print(basename+'>>>>'+'修改失败')
print('ok')