简体   繁体   English

在目录中查找名称中带有特殊字符的文件

[英]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]+/(.+)

Demo 1 演示1

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]+)

Demo 2 演示2

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

相关问题 有特殊字符问题的表名 - Table name with special character problem 在显示名称中使用特殊字符格式化电子邮件地址 - Format email address with special character in display name 难以在字符串中搜索和查找特殊的“\”字符? - Trouble to search and find the special “ \ ” character inside a string? 如何使用正则表达式查找特殊字符的出现 - how to find occurrence of special character using regex Python 3:如果文件不以特殊字符结尾,则加入文件行 - Python 3: Join lines of file if its not endswith a special character 在 python 中查找关键字后的字符串(包括其特殊字符) - Finding strings (including its special character) after keyword in python 查找目录中的所有csv文件,并将找到的文件按名称添加到正确的列表中 - Find all csv files in the directory and add found file to the proper list by its name SQL字符串在SQLIte列名称中引发带有特殊字符的错误 - SQL String throws error with special character in SQLIte column name 如何访问具有特殊字符名称的数据框中的列 - How to access columns in a dataframe having name with special character pattern.match无法识别带有特殊字符“ ^”的文件名(RegEx函数) - File name with special character “^” unrecognized by pattern.match (RegEx function)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM