The os.rename()
method in Python renames an existing file or directory.
import os
os.rename(oldname, newname)
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.
#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())
os
module. It comes with methods like makedirs
, mkdir
, listdir
, rename
, etc.Old directory
in the current directory.Old directory
to New directory
using the os.rename
method.