Python Regex作为目录路径escap的一部分

2024-09-28 22:29:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个按日期MMDDYYYY(11222013)命名的目录列表。我最终要删除2013年的所有目录。我相信我的正则表达式应该是6位数[0-9]。我尝试过将代码分解为多个变量,但没有成功。在

我怀疑我没有正确地逃离正则表达式。我一直遇到这样的错误:

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)

Tags: 代码testimport目录列表错误命名users
1条回答
网友
1楼 · 发布于 2024-09-28 22:29:33

这段代码可以做到:

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”结尾的“日期”文件夹。

相关问题 更多 >