[英]Find files in a dircetory with special character in its name
I tried to find files in a directory whose name include -
, ie /0.12345/Name-001-011
. 我试图在名称包括-
的目录中找到文件,即/0.12345/Name-001-011
。 Part of the code do it is like this 部分代码是这样的
mypath = '.'
pattern = '\d\.\d*/Name*/NameofFile'
fileList = []
for directory, dirnames, filenames in os.walk(mypath):
for name in filenames:
if re.search(pattern,os.path.join(directory,name)):
fileList.append(os.path.join(directory,name))
but unfortunately it does not find the file, and as I realised the problem stems from having -
in the path. 但遗憾的是它没有找到该文件,因为我意识到这个问题从具有茎-
路径。
The problem is that there is a missing dot in the regex pattern after Name
. 问题在于Name
后面的正则表达式模式中缺少点。 The correct pattern is below: 正确的模式如下:
/\d\.\d*/Name.*/NameofFile
As pointed out in the comments, by writing Name*
you tell the engine to match 0 or more repetitions of the character e
. 如注释中所指出,通过编写Name*
您告诉引擎匹配字符e
0个或多个重复。 Instead what you want presumably is to match anything after Name
which is achieved by .*
where dot stands for any character except newline. 取而代之的是,您想要的是在Name
之后匹配由.*
实现的任何内容,其中点表示除换行符以外的任何字符。
I'm guessing that our desired output would be Name-001-011
, which this simple expression would capture that: 我猜想我们想要的输出将是Name-001-011
,这个简单的表达式将捕获以下内容:
/[0-9]+\.[0-9]+/(.+)
If we might want to add Name
as a boundary and capture the digits, we can try: 如果我们想添加Name
作为边界并捕获数字,我们可以尝试:
/[0-9]+\.[0-9]+/Name-(.+)
or: 要么:
/[0-9]+\.[0-9]+/(Name-.+)
or: 要么:
/[0-9]+\.[0-9]+/(Name-[0-9]+-[0-9]+)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.