Created
May 3, 2018 08:31
-
-
Save gizalink/4912e8174c412324f3b0243a55189e62 to your computer and use it in GitHub Desktop.
Change file extension for multi file in sub-folder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Credit:https://gomputor.wordpress.com/2008/09/29/change-the-extension-of-multiple-files-in-a-chosen-directory-with-python/