Python Tutorials

Rename 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.

In the previous tutorial, we have seen renaming files by adding Prefix, now we are going to see renaming files by removing prefix.

So lets go with second case Removing Prefix to files.

First Create Python File Somewhere in your Laptop.

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

Previously we added a prefix “Friend” separating with “_” to the list of text files. Now we are going to remove the added previously added prefix “Friend” and also with that prefix we are also removing the separator “_”.

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)

    f_p, f_n = f_name.split('_')
 


    print('{}{}'.format(f_n, f_ext))

    new_name = '{}{}'.format(f_n, f_ext)

    os.rename(f, new_name)

Using above code you can remove suffix and rename multiple files at a time.

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

Leave a Reply

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

Back to top button