1

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?

amar96
  • 49
  • 5
  • You have the list of the files. You could iterate through each file (`for f in files:`), then check if the filename `startswith` the string you want, then [rename the file](https://stackoverflow.com/questions/2491222/how-to-rename-a-file-using-python) if necessary. – totok Jun 27 '22 at 09:37

1 Answers1

1

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")
amar96
  • 49
  • 5