So I was trying to match each line of a file to a regex and I did the following:
import re
regex='\S+\s+(\S{6})\s+VAR'
with open('/home/jyt109/humsavar.txt') as humsavar:
for line in humsavar:
match=regex.search(line)
print match.group(1)
Expected output is the particular 6 characters that are in each line, instead I get an error as below:
Traceback (most recent call last):
File "exercise.py", line 74, in <module>
match=regex.search(line)
AttributeError: 'str' object has no attribute 'search'
I have found out (from link below) that to match a regex to each line of a file, the file has to be first turned into a list by file.read()
Match multiline regex in file object
To readdress the post, is there any simpler way to do it (preferably over 1 line instead of 2)?
humsavar=open('/home/jyt109/humsavar.txt')
text=humsavar.read()
Thanks!