What is os.rename() in Python?
Overview
The os.rename() method in Python renames an existing file or directory.
Syntax
import os
os.rename(oldname, newname)
Parameters
We pass the old name of the file or directory as the first parameter, and the new name as the second parameter.
This method won’t return anything.
Let us take a look at an example.
Example
#Import the OS modulefrom os import mkdir, rename, listdir#Create the directorymkdir("./Old directory")#Print the list of files and directoriesprint(listdir())#Rename the directoryrename("Old directory", "New directory")#Print the list of files and directoriesprint(listdir())
Explanation
- Line 2: We import the
osmodule. It comes with methods likemakedirs,mkdir,listdir,rename, etc. - Line 5: We create a directory with
Old directoryin the current directory. - Line 11: We rename the
Old directorytoNew directoryusing theos.renamemethod.