amar96
amar96

Reputation: 49

Rename substring of actual files - python

I am reading in all the files in a given folder:

import os
    path = '/Users/user/Desktop/folder_name'
    files = os.listdir(path)

I have multiple files (100+) with the following names: 20220330_a.txt 20220330_b.txt 20220330_c.txt

I want to replace the "20220331" to "20220630" in the actual file names in the folder, so I obtain 20220630_a.txt, 20220630_b.txt etc.

Any ideas?

Upvotes: 1

Views: 32

Answers (1)

amar96
amar96

Reputation: 49

I figured it out myself:

old_date = "20200331"
new_date = "20200630"


for file in os.listdir(path):
    if file.startswith(old_date):
        if file.find(old_date) > -1:
            counter = counter + 1
            os.rename(os.path.join(path, file), os.path.join(path, file.replace(old_date,new_date)))
if counter == 0:
    print("No file has been found")

Upvotes: 1

Related Questions