python - 根据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()
解决方案
当您尝试使用时它说它没有显示为文件的原因 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]
您稍后在代码中的需要。
推荐阅读
- .net - NuGet“TargetFramework”缺少.Net参考编译错误......如何修复?
- couchdb - 如何确保 Hyperledger Fabric 对等方无法查看数据库?
- javascript - javascript在两个嵌套数组之间查找匹配的变量
- java - 获取“java.lang.String.org.json.JSONObject.getString(java.lang.String)”异常
- apache - APACHE 未在 Windows 10 中的 MAMP 上启动
- java - 使用注释的自定义跨度
- python - 使用python从不同目录一次下载数据的代码
- c# - 仅插入带有数据的记录(没有空记录)
- excel - 退出 If 和 Next For
- iis - 我在运行 PowerShell 时不断收到此错误