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 module
from os import mkdir, rename, listdir
#Create the directory
mkdir("./Old directory")
#Print the list of files and directories
print(listdir())
#Rename the directory
rename("Old directory", "New directory")
#Print the list of files and directories
print(listdir())

Explanation

  • Line 2: We import the os module. It comes with methods like makedirs, mkdir, listdir, rename, etc.
  • Line 5: We create a directory with Old directory in the current directory.
  • Line 11: We rename the Old directory to New directory using the os.rename method.

Free Resources