2017-12-20 48 views
0

날짜 MMDDYYYY (11222013)로 명명 된 디렉토리 목록이 있습니다. 나는 궁극적으로 2013 년부터 모든 디렉토리를 지우려고하고있다. 정규식은 6 자리 (0-9)를 찾아야한다고 나는 믿는다. 나는 여러 변수로 코드를 해봤지만 운이 없었습니다.Python - 디렉토리 경로의 일부인 Regex -

저는 정규 표현식을 올바르게 이스케이프하지 않을 것으로 생각합니다. 이 오류로 실행 계속 : 내 출력을 인쇄하려고했습니다

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

나는이 경로를 얻을 :

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

내 코드 :

import os 
import shutil 
import re 
StrDir = 'C:/Users/USER/Desktop/test/' 
Regex = r"\d{6}" + '13' 
print (StrDir + Regex) 
shutil.rmtree (StrDir + Regex) 
+0

당신은 정규식을 작성한 다음이를 문자열에 추가하여 문자열을 작성했습니다. 디렉토리 이름에 정규 표현식을 적용 할 곳이 없습니다. –

+0

[os.listdir] (https://docs.python.org/3/library/os.html#os.listdir) 또는 [os.walk] (https://docs.python.org)를 사용하는 것이 좋습니다. /3/library/os.html#os.walk)를 사용하여'^ \ d {4} 2013 $'정규식으로 이름을 반복하고 검사하십시오. [현재 디렉토리의 모든 하위 디렉토리 목록보기] (https://stackoverflow.com/questions/973473/getting-a-list-of-all-subdirectories-in-the-current-directory)를 참조하십시오. – Galen

답변

0
이 코드는 트릭을

해야 :

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) 

위의 코드 '2013'으로 끝나는 모든 '날짜'폴더를 제거합니다.