rename multiple files in a folder using python

Question:

i have a folder which has 3 types of files:

1.drizzle_refect_2020_10_10

2.reflexed_puzzlers_refect_2021_10_10

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

Asked By: dona

||

Answers:

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))
Answered By: noah1400
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.