How to rename a file using Python?

PythonServer Side ProgrammingProgramming

You can use os module's rename method. For example, you want to rename a file from a.txt to b.txt with these files present in your current directory,

>>> import os
>>> os.rename('a.txt', 'b.txt')

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
>>> shutil.move('a.txt', 'b.txt')

If you have the files in different directories, then specify the absolute path for both methods.

Published on 22-Dec-2017 12:08:44