需求:
- 模糊匹配指定路径下,且包含特定字符的文件名
- 只查找最后修改时间为1小时内的文件
import os
import time
import datetime
def transTime(file_time):
now = datetime.datetime.now()
#过期时间为1小时,可根据实际情况修改
deltaH = datetime.timedelta(seconds=3600)
f = datetime.datetime.fromtimestamp(os.path.getmtime(file_time))
if f > (now - deltaH):
return True
else:
return False
def find_file(dir, name):
pass_name = []
for i in [x for x in os.listdir(dir) if os.path.isfile(os.path.join(dir, x)) and name in os.path.splitext(x)[0]]:
# print(os.path.join(dir, i))
check_file = os.path.join(dir, i)
if (transTime(check_file)):
pass_name.append(check_file)
for i in [x for x in os.listdir(dir) if os.path.isdir(os.path.join(dir, x))]:
if os.listdir(os.path.join(dir, i)):
# 防止因为权限问题报错
try:
find_file(os.path.join(dir, i), name)
except:
pass
return pass_name
def main():
#脚本查找的路径,绝对路径
path=r"/Users/uuu/Desktop/222"
#模糊匹配条件'lib',可根据实际修改
file_yxb = find_file(path, 'lib')
print(file_yxb)
if __name__ == "__main__":
main()