Pythonで特定のタイプの最近変更された(ここから「最新」の)ファイルを見つけようとしています。現在最新のものを入手できますが、種類は問いません。最新の MP3 ファイルだけを取得したいのですが。
現在私は持っています:
import os
newest = max(os.listdir('.'), key = os.path.getctime)
print newest
これを変更して、最新の MP3 ファイルのみを提供する方法はありますか?
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)
この男を試してみてください:
import os
print max([f for f in os.listdir('.') if f.lower().endswith('.mp3')], key=os.path.getctime)