Rename a file in Python

To rename a file in Python 3 you just have to use the rename function of the os module. The code is really simple.

ยป More Python Examples

import os

# geekole.com

file = "/home/geekole/Documents/python/files/file.txt"
new_name = "/home/geekole/Documents/python/files/renamed_file.txt"

os.rename(file, new_name)

The function asks for the full path of the file and the full path of the file with the new name as parameters. If a file with the same name exists, it will overwrite it.

Rename a file in Python

When executing the code the file is renamed.

Rename a file in Python

We hope this example of how to rename a file in Python will be useful to you.