首页 > 解决方案 > 根据Python中的创建日期对文件列表进行排序

问题描述

我环顾四周,找不到解决方案的具体答案,此时我的大脑被炸了。我正在尝试根据文件夹中的一些 .bmp 文件创建 mp4 视频。但是,我想要按视频最早修改日期排序的文件。所以我使用的是最旧的修改日期。我在这里找到了一些关于使用 os.path.getmtime 的东西,但是如果我添加它告诉我它找不到文件。我猜这是因为文件位于网络上,而不是在我安装 python 的本地路径中。这是我的代码。我已经确认其他一切正常,所以我只需要找出如何对文件进行排序。

import cv2
import numpy as np
import os
from os.path import isfile, join

#change this to the path where the pictures are located
pathIn= #MyPathWhichIsOnANetworkNotWherePythonIsInstalled

#input your video name & video type:
vid_name = "FirstCalPics.mp4"

#change this to the path where the video should be saved:
pathSave = #AlsoAPathWhichIsOnANetworkNotWherePythonIsInstalled

#set your fps here:
fps = 10

pathOut = pathSave + vid_name

fourcc = cv2.VideoWriter_fourcc(*'mp4v')

frame_array = []
files = [f for f in os.listdir(pathIn) if isfile(join(pathIn, f))]

#Sort files based on date modified:
files.sort(key=os.path.getmtime)   #<--- HERE'S THE ISSUE

for i in range(len(files)):
    filename=pathIn + "\\" + files[i]
    #reading each files
    img = cv2.imread(filename)
    height, width, layers = img.shape
    size = (width,height)
    
    #inserting the frames into an image array
    frame_array.append(img)
out = cv2.VideoWriter(pathOut, fourcc, fps, size)

for i in range(len(frame_array)):
    # writing to a image array
    out.write(frame_array[i])
out.release()

标签: python

解决方案


当您尝试使用时它说它没有显示为文件的原因 justos.path.getmtime是因为您正在检查 just path,当您还有一个目录时:pathIn.

您可以join在排序时使用:

files.sort(key=lambda f: os.path.getmtime(join(pathIn, f)))

或者,(并且语法取决于您的 Python 版本)您可以直接存储最初的完整文件路径:

files = [fullPath for path in os.listdir(pathIn) if isfile((fullPath := join(pathIn, f)))]

这减轻了filename=pathIn + "\\" + files[i]您稍后在代码中的需要。


推荐阅读