Python Forum

Full Version: AttributeError: 'NoneType' re.search
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
python 3.12.1 Windows 11 command prompt (cmd)
TURN THIS:
this85_e1.txt
the other38_4e.asc
INTO THIS:
this
the other

This was working a few days ago and I thought I was running the
same code today. But now I get this error

File "C:\Users\phill\Documents\python\re_search_pub.py", line 9, in <module>
ln = line[0:pos.start()]
^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'start'

I did check out https://docs.python.org/dev/library/re.html
But can't figure out why [pos] is (now) a 'NoneType'

MY CODE:

import re   

ln = ""
pos = 0
output_file = open("bare.txt", "w") 
lines = open("filelist.asc", "r").readlines()
for line in lines:
pos = re.search(r"\d\d_\w\w", line)
    ln = line[0:pos.start()]
    output_file.write(ln + '\n')
output_file.close()
You read the documentation?
Quote:re.search(pattern, string, flags=0)
Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding Match. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.
search returns None if there is no pattern match. You need to check that search() returned a match before using the match.