All IT Courses 50% Off
Python Tutorials

Python Rename File and Directory using os.rename()

When working with servers you mostly get a terminal to perform different functions. Sometimes you need to write a different script that requires you to rename a file or directory. Let’s take a look at how to rename a file and directory using Python “os” library.

There is a python built-in function os.rename(src, dest) that take two arguments source location of the file or directory and destination location of the file or directory.

Renaming File

Python Rename File and Directory using os.rename()

Let’s run the following code.

import os

os.rename('rename-me.txt', 'i-am-file.txt')
Python Rename File and Directory using os.rename()

Renaming Directory

Now let’s rename the directory. Renaming directory is same as renaming file.

All IT Courses 50% Off
Python Rename File and Directory using os.rename()

Let’s execute the following code to rename the directory.

import os

os.rename('rename-dir', 'dir-renamed')
Python Rename File and Directory using os.rename()

Facebook Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Back to top button