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

Python 查找/删除目录中最旧的文件,python,file-io,path,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) 问题:问题以最小值法出现。\u文件的列表\u不包含完整路径,因此它尝试在当前目录中搜索文件

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

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)

问题:问题以最小值法出现。\u文件的列表\u不包含完整路径,因此它尝试在当前目录中搜索文件,但失败。如何将目录名('log')传递给min()?

os.listdir
将返回相对路径-这些路径与当前/当前工作目录/执行Python脚本的上下文相关(您可以通过
os.getcwd()
看到)

现在,
os.remove
函数需要一个完整路径/绝对路径-Shell/命令行接口可以推断出这一点,并代表您进行操作-但Python没有。您可以通过使用
os.path.abspath
,将代码更改为(并且由于os.listdir无论如何都会返回一个列表,因此我们不需要在其上添加列表comp来检查其长度):

这使它可以通用地知道它来自何处-即,在
os.listdir
的结果中产生的任何内容-您不必担心预先准备合适的文件路径。

使用理解(抱歉,无法抗拒):


我正努力实现与你一样的目标。并且面临着与
os.path.abspath()相关的类似问题
我使用的是带有python 3.7的windows系统

问题是
os.path.abspath()
给出了一个文件夹的位置 将“Yourpath”替换为文件所在文件夹的路径,代码应该可以正常工作

import os
import time

oldest_file = sorted([ "Yourpath"+f for f in os.listdir("Yourpath")], key=os.path.getctime)[0]

print (oldest_file)
os.remove(oldest_file)
print ("{0} has been deleted".format(oldest_file))`
必须有一些更干净的方法来做同样的事情
当我得到它时,我将进行更新。glob库一方面提供了完整的路径,并允许过滤文件模式。上述解决方案导致目录本身成为最旧的文件,这不是我想要的。对我来说,以下是合适的(glob和@Ivan Motin的混合)

import glob


sorted(glob.glob(“/home/pi/Pictures/*.jpg”),key=os.path.getctime)[0]

您看过
os.path.abspath
了吗?呃,这不是logrotate等工具的用途吗?
sorted(os.listdir(path),key=os.path.getctime)[0]
提供最旧的文件。sorted失败的原因与此相同。@srig这不是问题所在,使用
min()
在列表上进行排序是有效的,而将整个列表排序为第一个列表是无效的,这要感谢您指向logrotate。。python的新功能。。我要看看。。但是如果我能理解这里的错误就好了。如果listdir和日志文件在同一个位置,这会起作用-最好(通常不要重复使用文件的来源)使用
os.path.abspath
检索文件的完整路径名,然后
os.remove
实际上,这不是问题所在。。os.remove正确采用相对路径(python 3.7)。。问题在min()内。。文件列表只包含文件名“abc.log”,而不包含相对路径“log/abc.com”。。因此min()无法找到键..正在从'log'目录的父目录执行脚本。。也许我没有用那种方式表达这个问题。。
list_of_files = os.listdir('log')    

if len(list_of_files) >= 25:
    oldest_file = min(list_of_files, key=os.path.getctime)
    os.remove(os.path.abspath(oldest_file))
oldest_file = sorted([os.path.abspath(f) for f in os.listdir('log') ], key=os.path.getctime)[0]
import os
import time

oldest_file = sorted([ "Yourpath"+f for f in os.listdir("Yourpath")], key=os.path.getctime)[0]

print (oldest_file)
os.remove(oldest_file)
print ("{0} has been deleted".format(oldest_file))`