Find all text files not containing some text string

Viewed 2684

I'm on Python 2.7.1 and I'm trying to identify all text files that don't contain some text string.

The program seemed to be working at first but whenever I add the text string to a file, it keeps coming up as if it doesn't contain it (false positive). When I check the contents of the text file, the string is clearly present.

The code I tried to write is

def scanFiles2(rdir,sstring,extens,start = '',cSens = False): 
    fList = []
    for fol,fols,fils in os.walk(rdir): 
        fList.extend([os.path.join(rdir,fol,fil) for fil in fils if fil.endswith(extens) and fil.startswith(start)]) 
    if fList: 
        for fil in fList: 
            rFil = open(fil) 
            for line in rFil: 
                if not cSens: 
                    line,sstring = line.lower(), sstring.lower() 
                if sstring in line:
                    fList.remove(fil) 
                    break
            rFil.close() 
    if fList:
        plur = 'files do' if len(fList) > 1 else 'file does'
        print '\nThe following %d %s not contain "%s":\n'%(len(fList),plur,sstring) 
        for fil in fList: 
            print fil 
    else: 
        print 'No files were found that don\'t contain %(sstring)s.'%locals() 
scanFiles2(rdir = r'C:\temp',sstring = '!!syn',extens = '.html', start = '#', cSens = False) 

I guess there's a flaw in the code but I really don't see it.

UPDATE

The code still comes up with many false positives: files that do contain the search string but are identified as not containing it.

Could text encoding be an issue here? I prefixed the search string with U to account for Unicode encoding but it didn't make any difference.

Does Python in some way cache file contents? I don't think so but that could somewhat account for files to still pop up after having been corrected.

Could some kind of malware cause symptoms like these? Seems highly unlikely to me but I'm kinda desperate to get this fixed.

4 Answers
Related