import os
from datetime import datetime
def get_latest_file(folder):
latest = None
for file in os.listdir(folder):
path = os.path.join(folder, file)
if os.path.isfile(path):
modified_time = os.stat(path).st_mtime
# 若没有已知的最新文件,直接设置为当前文件
if not latest or modified_time > latest[0]:
latest = (modified_time, path)
return latest[1] if latest else "No files found."
# 测试
folder_path = "/path/to/your/folder"
latest_file = get_latest_file(folder_path)
print("Latest File:", latest_file)
注意事项:
get_latest_file()函数返回最新文件的完整路径。
/path/to/your/folder应替换为你想查找最新文件的文件夹路径。
该文章介绍了一个Python函数get_latest_file,它遍历指定文件夹内的文件,根据修改时间找出最新的文件并返回其完整路径。如果文件夹中没有文件,函数将返回Nofilesfound.。
2639

被折叠的 条评论
为什么被折叠?



