Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

rename multiple files in a folder using python

i have a folder which has 3 types of files:

1.drizzle_refect_2020_10_10

2.reflexed_puzzlers_refect_2021_10_10

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

3.squeeziest_donzel_refect_bench_123_20190711

i want the files to be renamed to as following:

1.drizzle_refect_543_2020_10_10

2.reflexed_puzzlers_refect_543_2021_10_10

3.squeeziest_donzel_refect_543_bench_123_20190711


date and number changes but the refect_ from the filename doesn’t change i want to rename that refect_ to refect_543_

i need a python code for that ….i want these files from a folder to be renamed..with a python code

>Solution :

You can create a list of files in a folder with os.listdir(foldername), then iterate over the files and replace refect_ with the command filename.replace after checking if refect_543_ is already present in the filename.
Renaming is done with os.rename

import os

foldername = "path/to/folder"

for filename in os.listdir(foldername)
    if not 'refect_543' in filename:
        new_file = filename.replace('refect_', 'refect_543_')
        os.rename(os.path.join(foldername, filename), os.path.join(foldername, new_file))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading