How to rename multiple files in a directory in Python?



If you have a list of files you want to rename and corresponding new file name, You can use os module's rename method.

For example

import os
for old, new in files.iteritems(): # files.items() in Python 3
    os.rename(old, new)

You can also use the shutil (or shell utilities) module. Calling shutil.move(source, destination) will move the file or folder at the path source to the path destination and will return a string of the absolute path of the new location.

For example

import shutil
for old, new in files.iteritems(): # files.items() in Python 3
    shutil.move(old, new)

Advertisements