1

I have a list of directories named by date MMDDYYYY (11222013). I'm ultimately trying to delete all directories from the year 2013. I believe my regex should be looking for 6 digits [0-9]. I've tried breaking the code into multiple variables but have had no luck.

I suspect I'm not escaping the regex correctly. I keep running into this error:

FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:/U sers/USER/Desktop/test/\d{6}13'

I've tried printing my output and I get this path:

C:/Users/USER/Desktop/test/\d{6}13

My code:

import os
import shutil
import re
StrDir = 'C:/Users/USER/Desktop/test/'
Regex = r"\d{6}" + '13'
print (StrDir + Regex)
shutil.rmtree (StrDir + Regex)
Killah G
  • 11
  • 3
  • You wrote a regex and then appended it to a string, creating a string. There's nowhere I'm setting you apply the regex to the directory names. – erik258 Dec 20 '17 at 23:39
  • You probably want to use [os.listdir](https://docs.python.org/3/library/os.html#os.listdir) or [os.walk](https://docs.python.org/3/library/os.html#os.walk) to iterate and check names with the regex `^\d{4}2013$`. See [Getting a list of all subdirectories in the current directory](https://stackoverflow.com/questions/973473/getting-a-list-of-all-subdirectories-in-the-current-directory). – Galen Dec 20 '17 at 23:47

1 Answers1

1

This code should do the trick:

import os
import shutil
import re

pattern = "^\d{4}2013$"
searchDir = 'C:/Users/USER/Desktop/test/'
innerDirs = os.listdir(searchDir)
for dir in innerDirs:
    if (re.search(pattern, dir)):
        shutil.rmtree(searchDir + dir) 

The code above will remove any "date" folder that ends with '2013'.

oBit91
  • 398
  • 1
  • 12