我正在尝试使用 Python 中的正则表达式将文件(保存为字符串,即“/volumes/footage/foo/bar.mov”)与我创建的包含文件列表的日志文件相匹配。但是当我运行脚本时,它给我这个错误:sre_constants.error: unbalanced parenthesis
。我使用的代码是这样的:
读取文件:
theLogFile = The_Root_Path + ".processedlog"
if os.path.isfile(theLogFile):
the_file = open(theLogFile, "r")
else:
open(theLogFile, 'w').close()
the_file = open(theLogFile, "r")
the_log = the_file.read()
the_file.close()
然后在 for
循环中,我将 the_file
变量重新分配(我没有意识到我在做这个,直到我发布了这个问题)文件(通过运行文件夹及其子集并获取所有文件名获得),然后尝试使用正则表达式查看该文件名是否存在于日志文件中:
for the_file in filenamelist:
p = re.compile(the_file, re.IGNORECASE)
m = p.search(the_log)
每次它遇到代码的 re.compile()
部分时,它都会吐出该错误。如果我尝试将其删除并使用 re.search(the_file, the_log)
,它仍然会吐出该错误。我不明白我怎么会因此得到不平衡的括号。
最佳答案
正则表达式模式在哪里?您是否尝试使用一个文件中包含的文件名作为模式来搜索另一个文件?如果是这样,您将希望通过 the_file
来执行类似
for the_pattern in the_file:
p = re.compile(the_pattern, re.IGNORECASE)
m = p.search(the_log)
...
根据 the Python re.compile
documentation ,re.compile()
的第一个参数应该是作为字符串的正则表达式模式。
但是 open()
的返回值是一个文件对象,您将其分配给 the_file
并传递给 re.compile()
....
关于Python Regex 匹配文件列表中的文件(出错),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2344193/