Python:在目录中查找带有 .MP3 扩展名的最新文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18279063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:21:50  来源:igfitidea点击:

Python: Find newest file with .MP3 extension in directory

pythonfile-io

提问by Butters

I am trying to find the most recently modified (From here on out 'newest') file of a specific type in Python. I can currently get the newest, but it doesn't matter what type. I would like to only get the newest MP3 file.

我试图在 Python 中找到特定类型的最近修改的(从这里开始的“最新”)文件。我目前可以获得最新的,但不管是什么类型。我只想获取最新的 MP3 文件。

Currently I have:

目前我有:

import os

newest = max(os.listdir('.'), key = os.path.getctime)
print newest

Is there a way to modify this to only give me only the newest MP3 file?

有没有办法修改它只给我最新的 MP3 文件?

采纳答案by falsetru

Use glob.glob:

使用glob.glob

import os
import glob
newest = max(glob.iglob('*.[Mm][Pp]3'), key=os.path.getctime)

回答by scohe001

Give this guy a try:

试试这个人:

import os
print max([f for f in os.listdir('.') if f.lower().endswith('.mp3')], key=os.path.getctime)

回答by Kevin Vincent

Assuming you have imported os and defined your path, this will work:

假设您已导入 os 并定义了您的路径,这将起作用:

dated_files = [(os.path.getmtime(fn), os.path.basename(fn)) 
               for fn in os.listdir(path) if fn.lower().endswith('.mp3')]
dated_files.sort()
dated_files.reverse()
newest = dated_files[0][1]
print(newest)

回答by Arjun Krishna

for file in os.listdir(os.getcwd()):
    if file.endswith(".mp3"):
        print "",file
        newest = max(file , key = os.path.getctime)
        print "Recently modified Docs",newest

回答by Michael S.

For learning purposes here my code, basically the same as from @Kevin Vincent though not as compact, but better to read and understand:

出于学习目的,我的代码与@Kevin Vincent 的代码基本相同,虽然不那么紧凑,但更易于阅读和理解:

import datetime
import glob
import os

mp3Dir = "C:/mp3Dir/"
filesInmp3dir = os.listdir(mp3Dir)

datedFiles = []
for currentFile in filesInmp3dir:
    if currentFile.lower().endswith('.mp3'):
        currentFileCreationDateInSeconds = os.path.getmtime(mp3Dir + "/" + currentFile)
        currentFileCreationDateDateObject = datetime.date.fromtimestamp(currentFileCreationDateInSeconds)
        datedFiles.append([currentFileCreationDateDateObject, currentFile])
        datedFiles.sort();
        datedFiles.reverse();

print datedFiles
latest = datedFiles[0][1]
print "Latest file is: " + latest