Python Rename File

Python Rename File and Directory using os.rename()

In Python programming, the process of renaming a file or directory can be accomplished with the help of the rename() file method. It is possible to specify the Python rename() file method by giving two parameters known as src (which stands for Source) and dst (Destination).

The syntax for the os.rename() method is as follows:

os.rename (src, dst)
The name of the file or directory is referred to as src, which stands for “source.” It should have already been in place.

dst: Destination is the new name that you would like to give to the directory or file that you are modifying.


import os os.rename(‘guru99.txt’,’career.guru99.txt’)
Let’s look at example in detail

You are free to rename the original file; in our case, we renamed the file to “Career.guru99.txt” from the previous name, “Guru99.txt.”

Shell Script Commands and Python Operating System Modules
We are going to use the “rename function” that is located in the OS module in order to rename the file “guru99.txt.”
Therefore, when you run the code, you will notice that a new file with the name “career.guru99.txt” is produced on the right-hand side of the panel. This is because we renamed the file we were working with before running the code.
This is the final version of the code.

os import shutil should be imported from the os import path.

def main():

# create a copy of an already existing file if the path already contains “guru99.txt”:

# Obtain the path to the file that is located in the active directory src = path.realpath(“guru99.txt”);

# rename the initial file with the command os.rename(‘guru99.txt’,’career.guru99.txt’)
If __name__ is equal to “__main__,” then the main ()