57

Pythonで特定のタイプの最近変更された(ここから「最新」の)ファイルを見つけようとしています。現在最新のものを入手できますが、種類は問いません。最新の MP3 ファイルだけを取得したいのですが。

現在私は持っています:

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

これを変更して、最新の MP3 ファイルのみを提供する方法はありますか?

4

6 に答える 6

11

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)
于 2013-08-16T18:16:51.500 に答える
2

この男を試してみてください:

import os
print max([f for f in os.listdir('.') if f.lower().endswith('.mp3')], key=os.path.getctime)
于 2013-08-16T17:50:14.197 に答える