Advertisement
phy_bunny

Search for special file type

Mar 2nd, 2025
262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.41 KB | Software | 0 0
  1. import os
  2. import glob
  3.  
  4. def find_latest_file(folder_path, file_extension, keyword):
  5.     # 构建搜索模式
  6.     search_pattern = os.path.join(folder_path, f'*.{file_extension}')
  7.    
  8.     # 获取匹配的文件列表
  9.     files = glob.glob(search_pattern)
  10.    
  11.     if not files:
  12.         print("没有找到匹配的文件。")
  13.         return None
  14.    
  15.     # 初始化变量以存储最新文件的信息
  16.     latest_file = None
  17.     latest_time = 0
  18.    
  19.     # 遍历所有找到的文件
  20.     for file in files:
  21.         # 检查文件名中是否包含指定的关键字
  22.         if keyword in os.path.basename(file):
  23.             # 获取文件的修改时间
  24.             file_mod_time = os.path.getmtime(file)
  25.            
  26.             # 如果当前文件的修改时间比最新的还要新,更新最新文件信息
  27.             if file_mod_time > latest_time:
  28.                 latest_time = file_mod_time
  29.                 latest_file = file
  30.            
  31.     return latest_file
  32.  
  33. # 使用示例
  34. folder_path = 'D:\document\python_project\physics_simulation\EDMD\Single'  # 替换为你的文件夹路径
  35. file_extension = 'sph'  # 替换为你要查找的文件扩展名
  36. keyword = 'mov'  # 需要检测的关键字
  37.  
  38. latest_file = find_latest_file(folder_path, file_extension, keyword)
  39.  
  40. if latest_file:
  41.     print(f"最新的文件是: {latest_file}")
  42. else:
  43.     print("没有找到包含关键字的文件。")
  44.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement