Users Online

· Guests Online: 142

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

PY0019 Python Rename File and Directory using os.rename()

In Python, rename() method is used to rename a file or directory. It takes two arguments. Let's check the syntax.

Syntax

This is the syntax for os.rename() method

os.rename(src, dst)

Parameters

src: Source is the name of the file or directory. It should must already exist.

dst: Destination is the new name of the file or directory you want to change.

Example:

import os  
os.rename('guru99.txt','career.guru99.txt') 

Let's look at example in detail

You can rename the original file, we have changed the file name from "Guru99.txt" to "Career.guru99.txt."

Python OS Module, Shell Script Commands

  • To rename "guru99.txt" file, we going to use "rename function" in the OS module
  • So when the code is executed, you can observe that a new file "career.guru99.txt" is created on the right side of the panel, which we renamed for our original file.

Here is the complete code

import os
import shutil
from os import path

def main():
	# make a duplicate of an existing file
    if path.exists("guru99.txt"):
	# get the path to the file in the current directory
        src = path.realpath("guru99.txt");
		
	# rename the original file
        os.rename("career.guru99.txt","guru99.txt")
		
if __name__ == "__main__":
    main()

 

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.80 seconds
10,814,477 unique visits