我有一个名为“FILENAME.TXT”文件Python的正则表达式NoneType错误
内容的文本文件:
This is just a text
content to store
in a file.
我已经做了两个Python脚本来提取“到”从文本文件
我的第一脚本:
#!/usr/bin/python
import re
f = open("filename.txt","r")
for line in f:
text = re.match(r"content (\S+) store",line)
x = text.group(1)
print x
我的第二个脚本:
#!/usr/bin/python
import re
f = open("filename.txt","r")
for line in f:
text = re.match(r"content (\S+) store",line)
if text:
x = text.group(1)
print x
第二脚本提供了正确的输出
bash-3.2$ ./script2.py
to
但第一次剧本给我一个错误
bash-3.2$ ./script1.py
Traceback (most recent call last):
File "./script1.py", line 6, in ?
x = text.group(1)
AttributeError: 'NoneType' object has no attribute 'group'
怎么就是添加一个“如果”条件给我正确的输出,当我删除它我得到一个错误?