python - 查找/删除目录中最旧的文件

标签 python file-io path

当文件数达到阈值时,我试图删除目录中最旧的文件。

list_of_files = os.listdir('log')    

if len([name for name in list_of_files]) == 25:
    oldest_file = min(list_of_files, key=os.path.getctime)
    os.remove('log/'+oldest_file)

问题:问题出在 min 方法中。 list_of_files 不包含完整路径,因此它试图在当前目录中搜索文件并失败。如何将目录名称('log')传递给 min()?

最佳答案

list_of_files = os.listdir('log')
full_path = ["log/{0}".format(x) for x in list_of_files]

if len(list_of_files) == 25:
    oldest_file = min(full_path, key=os.path.getctime)
    os.remove(oldest_file)

关于python - 查找/删除目录中最旧的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47739262/

相关文章:

python - 在Python中按任何按键时停止keyboard.record()函数

python - 对图的顶点重新排序。它应该像彼得森图一样排序

python - Matplotlib 在我的 Linux 机器上找不到安装的字体

c++ - C++ 从文件中读取输入

c++ - Win32 API 中 PathAppend 和 PathCombine 的区别

c# - Visual Studio 2012 正在错误的路径中搜索项目?

python - 使用 websocket.send(msg) 一段时间后出现 "got Future <Future pending> attached to a different loop"错误

java - 尝试实现 Java 套接字示例的问题

c - 使用相对路径打开文件失败

java - 我的 $PATH 变量集的全局配置在哪里?