Python Tutorials

Renaming All Files in a Folder With Python

Hello Guys,

In this Python Tutorial, We are going to learn how to Rename Files with Python.

Actually there is no problem if we are renaming one or two files, but when we want to rename many files in bulk then the problem begins. It is not easy to rename many files.

Then We came with a Solution. With the help of Python, we can rename as many files as we want all at once in One Click.

There are many types in Renaming a file. In some cases, you want to add Prefix, in some you want to add Sufix. In Some Cases, you want to remove either Prefix or Sufix.

So lets start with first case Adding a Prefix to files

With No Delay Let’s Get Started.

First Create Python File Somewhere in your Laptop.

Now Open the Python file in Editor Mode. Start writing this code.

So There are many text files with names of your friends in a folder and you decided to add a prefix “Friend” separating with “_” for the name of each file as shown in the image below.

Renaming Friends Text Files

So Let’s see how the code goes.

import os

os.chdir("C:\\Users\\Ramesh Naidu\\Desktop\\Code World\\Python Tutorials\\Rename Files")


for f in os.listdir():
    

    f_name, f_ext = os.path.splitext(f)


    frnd = ['Friend']

    frnd_n = f_name.join(frnd)  


    print('{}_{}{}'.format(frnd_n, f_name, f_ext))

    new_name = '{}_{}{}'.format(frnd_n, f_name, f_ext)

    os.rename(f, new_name)

After Running this Code the Output is

Output Renaming Friends Text Files

So Here is the Output of renaming all files at Once in One Click.

Note: Change os.chdir path to your own.

That’s it Now you can Rename multiple files by adding Prefix all at Once.

In the Next Tutorial we’ll see about Renaming all Files by adding Sufix

KSR

Hi there! I am the Founder of Cyber World Technologies. My skills include Android, Firebase, Python, PHP, and a lot more. If you have a project that you'd like me to work on, please let me know: contact@cyberworldtechnologies.co.in

Related Articles

Back to top button