简体   繁体   English

Python-正则表达式作为目录路径的一部分-转义

[英]Python - Regex as part of directory path - escape

I have a list of directories named by date MMDDYYYY (11222013). 我有一个以日期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]. 我最终试图删除2013年以来的所有目录。我相信我的正则表达式应查找6位数字[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' FileNotFoundError:[WinError 3]系统找不到指定的路径:'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 C:/用户/用户/桌面/测试/ \\ 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)

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'. 上面的代码将删除所有以'2013'结尾的“日期”文件夹。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM