Python 检查路径中是否存在某些文件夹
我正在迭代文件夹,逐行读取文件,以便找到一些子字符串 问题是我想在搜索过程中忽略一些文件夹(如Python 检查路径中是否存在某些文件夹,python,Python,我正在迭代文件夹,逐行读取文件,以便找到一些子字符串 问题是我想在搜索过程中忽略一些文件夹(如bin或build) 我试图添加检查-但它仍然包括在搜索中 def step(ext, dirname, names): for name in names: if name.lower().endswith(".xml") or name.lower().endswith(".properties") or name.lower().endswith(".java"):
bin
或build
)
我试图添加检查-但它仍然包括在搜索中
def step(ext, dirname, names):
for name in names:
if name.lower().endswith(".xml") or name.lower().endswith(".properties") or name.lower().endswith(".java"):
path = os.path.join(dirname, name)
if not "\bin\"" in path and not "\build" in path:
with open(path, "r") as lines:
print "File: {}".format(path)
i = 0
for line in lines:
m = re.search(r"\{[^:]*:[^\}]*\}", line)
with open("search-result.txt", "a") as output:
if m is not None:
output.write("Path: {0}; \n Line number: {1}; \n String: {2}\n".format(path, i, m.group()))
i+=1
我怀疑您的条件失败是因为
\b
被解释为退格字符,而不是后跟“b”字符的反斜杠字符。此外,它看起来像是你在逃避一个引号在最后的垃圾箱;这是故意的吗
试着避开反斜杠
if not "\\bin\\" in path and not "\\build" in path:
我会做这项工作,但我更愿意让别人来做这项工作(因此,如果有人在不同的平台上使用该功能,它就会工作):
我不知道OP是否在Windows上运行此代码。可能他应该使用
os.path.sep
而不是'\\'
import os.path
def path_contains(path, folder):
while path:
path, fld = os.path.split(path)
# Nothing in folder anymore? Check beginning and quit
if not fld:
if path == folder:
return True
return False
if fld == folder:
return True
return False
>>> path_contains(r'C:\Windows\system32\calc.exe', 'system32')
True
>>> path_contains(r'C:\Windows\system32\calc.exe', 'windows')
False
>>> path_contains(r'C:\Windows\system32\calc.exe', 'Windows')
True
>>> path_contains(r'C:\Windows\system32\calc.exe', 'C:\\')
True
>>> path_contains(r'C:\Windows\system32\calc.exe', 'C:')
False
>>> path_contains(r'C:\Windows\system32\calc.exe', 'test')
False