Batch Rename File Extensions
Medium
Write a function new_extensions(filenames, old_ext, new_ext) that takes a list of filename strings, and for any filename ending with old_ext, returns a new list where that extension is replaced with new_ext. Filenames not matching old_ext are left unchanged.
Input
A list of filenames (strings), and two extension strings (e.g. ".jpeg" and ".jpg").
Output
A list of filenames with extensions replaced where applicable.
Example
Input
filenames=["photo1.jpeg", "photo2.jpeg", "notes.txt"], old_ext=".jpeg", new_ext=".jpg"
Output
['photo1.jpg', 'photo2.jpg', 'notes.txt']
Use str.endswith(old_ext) to check each filename, and if it matches, use slicing or replace to swap the extension. Build the result with a list comprehension.
15 XP on solve
Back to lesson
Your Solution
Output
Click "Run" to execute your code...
⏳ Loading Python runtime (first run may take a few seconds)...
Log in to submit your solution and earn XP.