're.search returning None type depeding on os syntax used

I'm practicing with os and re to search multiple files.

I had an issue with re.search returning None when it found the correct string.

I started over after much frustration and in my second iteration, it works. but my question is, why do I get a different result between my 1st and 2nd attempts:

1st attempt (returning None):

for root,sub,file in os.walk(curr_dir):
     for f in file:
        name = open(os.path.join(root,f),"r")
       
        if re.search(r"\w",name.read()):
            print (f"{os.path.join(root,f)}")
            print (re.search(r"\w",name.read()))

note it does correctly print out {os.path.join(root,f)} for the file containing text

2nd attempt (works great):

for root, dirs, files in os.walk(curr_dir):
    for f in files:
        t= open(os.path.join(root,f),"r")
        text = t.read()
                
        if re.search(r"\w",text):
            print (re.search(r"\w",text)

The only change is that in the second attempt I assign .read() to a variable (text) rather than call read in the r.search. But I don't understand why that would change the result type..

Thanks,

Glovey



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source