Python 3 - os.rename() Method


Description

The method rename() renames the file or directory src to dst.If dst is a file or directory(already present), OSError will be raised.

Syntax

Following is the syntax for rename() method −

os.rename(src, dst)

Parameters

  • src − This is the actual name of the file or directory.

  • dst − This is the new name of the file or directory.

Return Value

This method does not return any value.

Example

The following example shows the usage of rename() method.

# !/usr/bin/python3
import os, sys
os.chdir("d:\\tmp")

# listing directories
print ("The dir is: %s"%os.listdir(os.getcwd()))

# renaming directory ''tutorialsdir"
os.rename("python3","python2")

print ("Successfully renamed.")

# listing directories after renaming "python3"
print ("the dir is: %s" %os.listdir(os.getcwd()))

Result

When we run the above program, it produces the following result −

The dir is: [
   'Applicationdocs.docx', 'book.zip', 'foo.txt', 
   'Java Multiple Inheritance.htm', 'Java Multiple Inheritance_files', 
   'java.ppt', 'Python3'
]

Successfully renamed.

the dir is: [
   'Applicationdocs.docx', 'book.zip', 'foo.txt', 
   'Java Multiple Inheritance.htm', 'Java Multiple Inheritance_files',
   'java.ppt', 'python2'
]
python_files_io.htm
Advertisements