Skip to content

Instantly share code, notes, and snippets.

@DBoyara
Last active February 25, 2021 09:28
Show Gist options
  • Save DBoyara/8ec305f893fa34a8ebe1cad64fa3ae21 to your computer and use it in GitHub Desktop.
Save DBoyara/8ec305f893fa34a8ebe1cad64fa3ae21 to your computer and use it in GitHub Desktop.
Changing the names of files and directories in the specified directory
import os
def main(my_path: str, replace_name: str):
for dirpath, dirnames, filenames in os.walk(my_path):
for dirname in dirnames:
dir_old_name = os.path.join(dirpath, dirname)
if dir_old_name.find(replace_name) != -1:
dir_new_name = dir_old_name.replace(replace_name, "")
os.rename(dir_old_name, dir_new_name)
for filename in filenames:
file_old_name = os.path.join(dirpath, filename)
if file_old_name.find(replace_name) != -1:
file_new_name = file_old_name.replace(replace_name, "")
os.rename(file_old_name, file_new_name)
if __name__ == '__main__':
main("path", "replace_pattern")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment