Python | os.rename() method

Last Updated : 19 Jun, 2026

os.rename() method is used to rename a file or directory. It changes the current name or path of a file or folder to a new name or path specified by the user.

Example: In the following example, we rename a file from old.txt to new.txt.

Python
import os
os.rename("old.txt", "new.txt")
print("File renamed successfully")

Output

File renamed successfully

Explanation: os.rename("old.txt", "new.txt") changes the name of the file from old.txt to new.txt.

Syntax

os.rename(src, dst)

  • Parameters: fd - The file descriptor to be closed.
  • Return Value: os.close() does not return any value.

Examples

Example 1: The following example opens a file in read mode and then closes its file descriptor.

Python
import os
fd = os.open("sample.txt", os.O_RDONLY)
print("Descriptor:", fd)
os.close(fd)

Output

Descriptor: 3

Explanation: os.open() creates a file descriptor and stores it in fd. The statement os.close(fd) closes that descriptor.

Example 2: The following example opens a file in write mode, writes data to it and then closes the file descriptor.

Python
import os

fd = os.open("data.txt", os.O_WRONLY | os.O_CREAT)
os.write(fd, b"Hello Python")
os.close(fd)
print("Data written successfully")

Output

Data written successfully

Explanation: os.write(fd, b"Hello Python") writes data to the file associated with fd. After writing, os.close(fd) releases the file descriptor.

Example 3: The following example opens two files and closes both file descriptors separately.

Python
import os

fd1 = os.open("a.txt", os.O_RDONLY)
fd2 = os.open("b.txt", os.O_RDONLY)

os.close(fd1)
os.close(fd2)
print("Both descriptors closed")

Output

Both descriptors closed

Explanation: os.close(fd1) closes the first file descriptor and os.close(fd2) closes the second one, releasing both resources.

Comment