我试图制作一个程序来搜索目录的.txt
文件,并通过regex标记其内容与用户输入匹配的任何文件。
os.chdir(folder)
variableRegex = re.compile(variable)
for file in os.listdir(folder):
if file.endswith('.txt'):
filename = file
open(file)
open(file).read()
file = variableRegex.search(open(file).read())
if file.group() is None:
print(filename + " negative.")
else:
print(filename + " positive.")
当file.group()
不等于None
时,即当有匹配时,程序运行。但是,当file.group()等于0时,程序返回一个错误,即使这是我希望在这个程序中发生的正常函数。
Set what variable to analyze for.
al
Set what folder to analyze.
C:\regextest
regex1.txt positive.
Traceback (most recent call last):
File "C:\Users\<myembarrassingusername>\AppData\Local\Programs\Python\Python38\automatepython\regexsearch.py", line 20, in <module>
if file.group() is None:
AttributeError: 'NoneType' object has no attribute 'group'
目录C:\regextest
有两个.txt
文件,第一个文件有'al‘,另一个文件中有不同的名称。如何使此程序在不接收错误的情况下接受None
值?
如果您有兴趣的话,变量和文件夹变量是在输入()之前输入的。
发布于 2020-11-25 22:07:42
添加了检查变量file
是否为None
类型的代码
os.chdir(folder)
variableRegex = re.compile(variable)
for file in os.listdir(folder):
if file.endswith('.txt'):
filename = file
open(file)
open(file).read()
file = variableRegex.search(open(file).read())
#Added Code Here
NoneType=type(None)
if(type(file)!=NoneType):
if file.group() is None:
print(filename + " negative.")
else:
print(filename + " positive.")
else:
print("Your Logic Here to Handle Such Cases")
https://stackoverflow.com/questions/65016673
复制相似问题