There is often a need to find a specific string in a text file, which is very well implemented and can be done almost anywhere with any text viewing tool. And sometimes, to find all the text files in a folder (a specific suffix), I have this problem: I want to find the source code of blender for the SPH implementation code. Then wrote the following simple program:
#!/usr/bin/env python3import osdef Search (rootdir, suffixes, arg): For lists in Os.listdir (ROOTDIR): path = Os.path.join (RootDir, lists) if Os.path.isfile (path): if Path.endswith (suffixes): try: with open ( Path, encoding= ' Utf_8 ') as FH: linenum = 0 for line in FH: linenum + = 1 if arg in line: print (linenum , ': ', path, ' \ n ', line) fh.close () except: print (' ERROR: ', path, ' \ n ') if Os.path.isdir (path): C15/>search (path, suffixes, arg) Search (R ' D:\blender-2.70 ', ('. C ', '. cpp ', '. h ', '. hpp '), ' SPH ')
Although the program is small, but very practical, the operation results are as follows:
Python implements recursive lookup of text files within folders