Python OS – Rename a file using Python

In this post we will be creating a Python script that will enable us to rename files. To do this we will be using the OS module which provides a portable way of using operating system dependent functionality. In particular we will be making use of the ‘rename()’ method which renames the specified file or directory.

Note that if the destination of our newly named file already exists the function will fail and so we will introduce some error handling via a try and except block. See the snippet of code as an example.

import os


    os.rename(old_file_name, new_file_name)
except OSError as e:  
    print ("Error: %s - %s." % (e.filename, e.strerror))

Leave a Reply