Rename multiple files in a directory in Python [duplicate] Rename multiple files in a directory in Python [duplicate] python python

Rename multiple files in a directory in Python [duplicate]


Use os.rename(src, dst) to rename or move a file or a directory.

$ lscheese_cheese_type.bar  cheese_cheese_type.foo$ python>>> import os>>> for filename in os.listdir("."):...  if filename.startswith("cheese_"):...    os.rename(filename, filename[7:])... >>> $ lscheese_type.bar  cheese_type.foo


Here's a script based on your newest comment.

#!/usr/bin/env pythonfrom os import rename, listdirbadprefix = "cheese_"fnames = listdir('.')for fname in fnames:    if fname.startswith(badprefix*2):        rename(fname, fname.replace(badprefix, '', 1))


The following code should work. It takes every filename in the current directory, if the filename contains the pattern CHEESE_CHEESE_ then it is renamed. If not nothing is done to the filename.

import osfor fileName in os.listdir("."):    os.rename(fileName, fileName.replace("CHEESE_CHEESE_", "CHEESE_"))