簡體   English   中英

根據 Python 中的創建日期對文件列表進行排序

[英]Sort list of files based on creation date in Python

我環顧四周,找不到解決方案的具體答案,此時我的大腦被炸了。 我正在嘗試基於文件夾中的 some.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()

當您嘗試僅使用os.path.getmtime時它說它不顯示為文件的原因是因為您正在檢查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]的需求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM