Python Rename File and Directory using os.rename()

Table of Contents

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.

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()

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.

Share this article
Subscribe
By pressing the Subscribe button, you confirm that you have read our Privacy Policy.
Need a Free Demo Class?
Join H2K Infosys IT Online Training
Enroll Free demo class