Python检查文件中的最新图像

2024-06-10 00:55:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在文件夹中获取最新的图像文件,以下是我尝试的内容:

import os.path
import os

path = 'C:/Users/William/Desktop/Test Utk Deploy/Image Dir'

if len(os.listdir(path) ) == 0:
    print("Directory is empty")
else:
    files = []
    for file in os.listdir(path):
        if file.endswith(".png") or file.endswith(".jpg") or file.endswith(".jpeg") or file.endswith(".PNG") or file.endswith(".JPG") or file.endswith(".JPEG"):
            files.append(file)
    print(max(files , key = os.path.getctime))   

然而,我得到了这个错误

runfile('C:/Users/William/Desktop/Test Utk Deploy/deploy.py', wdir='C:/Users/William/Desktop/Test Utk Deploy')
Traceback (most recent call last):

  File "C:\Users\William\Desktop\Test Utk Deploy\deploy.py", line 24, in <module>
    newest = max(files , key = os.path.getctime)

  File "C:\Users\William\anaconda3\envs\faceRecog\lib\genericpath.py", line 65, in getctime
    return os.stat(filename).st_ctime

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'Capture.PNG'

所以我认为问题在于我的程序在文件数组中找不到最新的文件(实际上是Capture.PNG)。然后出于好奇,我试着打印文件数组

print(files)

这就是结果

['Capture.PNG', 'Screenshot (13).png']

根据结果,文件Capture.PNG似乎已成功存储在文件数组中。但是当我运行print(max(files,key=os.path.getctime))代码时,我的程序会显示这个错误。有人能帮忙吗?提前谢谢


Tags: orpathtestpngosfilesusersdeploy
1条回答
网友
1楼 · 发布于 2024-06-10 00:55:14

模块os.path.getctime获取指定路径的系统的ctime。您的列表仅包括文件名,而不包括其完整路径。当试图打印时间时,它会在默认目录(可能是您调用脚本的目录)中查找文件,而该目录不是文件的实际位置

您可以通过将完整目录附加到名称来解决此问题,如下所示:

files.append('%s/%s'.format(path,file))

请注意,我的知识有点陈旧,但类似的东西应该有用

相关问题 更多 >