Python: Find newest file with .MP3 extension in directory

后端 未结 5 980
别那么骄傲
别那么骄傲 2020-12-12 17:55

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

相关标签:
5条回答
  • 2020-12-12 18:30

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

    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
    
    0 讨论(0)
  • 2020-12-12 18:32

    Give this guy a try:

    import os
    print max([f for f in os.listdir('.') if f.lower().endswith('.mp3')], key=os.path.getctime)
    
    0 讨论(0)
  • 2020-12-12 18:40

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

    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)
    
    0 讨论(0)
  • 2020-12-12 18:41

    Use glob.glob:

    import os
    import glob
    newest = max(glob.iglob('*.[Mm][Pp]3'), key=os.path.getctime)
    
    0 讨论(0)
  • 2020-12-12 18:42
    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
    
    0 讨论(0)
提交回复
热议问题