I have multiple files that contain the date. for example the file names are :
one08172021patient.txt
two09182021patient.txt
three09182021patient.txt
I would to write a script in Python to create folder for year ,month,day and move the file based on the date that's already in the file name. I have looked around for this logic in google but i didn't get any. result for this case.
After running the code the result will be similar to this :
+---2021
| \---08
| ----17 one08172021patient.txt
|
\---2021
+---09
------18
two09182021patient.txt
You can use this script:
import re
from os import walk, rename
from pathlib import Path
src_path = './src'
des_path = './dst'
filenames = next(walk(src_path), (None, None, []))[2]
for file in filenames:
match = re.search(r'^\D+(\d{2})(\d{2})(\d{4})', file)
if match:
month = match.group(1)
day = match.group(2)
year = match.group(3)
path = f'{des_path}/{year}/{month}/{day}'
Path(path).mkdir(parents=True, exist_ok=True)
rename(f'{src_path}/{file}', f'{path}/{file}')