Skip to content

Instantly share code, notes, and snippets.

@gizalink
Created May 3, 2018 08:31
Show Gist options
  • Save gizalink/4912e8174c412324f3b0243a55189e62 to your computer and use it in GitHub Desktop.
Save gizalink/4912e8174c412324f3b0243a55189e62 to your computer and use it in GitHub Desktop.
Change file extension for multi file in sub-folder
import os
def change_file_ext(cur_dir, old_ext, new_ext, sub_dirs=False):
if sub_dirs:
for root, dirs, files in os.walk(cur_dir):
for filename in files:
file_ext = os.path.splitext(filename)[1]
if old_ext == file_ext:
oldname = os.path.join(root, filename)
newname = oldname.replace(old_ext, new_ext)
os.rename(oldname, newname)
else:
files = os.listdir(cur_dir)
for filename in files:
file_ext = os.path.splitext(filename)[1]
if old_ext == file_ext:
newfile = filename.replace(old_ext, new_ext)
os.rename(filename, newfile)
change_file_ext('C:/Users/xxxx/Desktop/abc', '.html', '.txt', True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment