Search code examples
pythonstartswith

find string line startswith recursively python


i have to find recursively all lines( which start with string "excel") in all files (in directory and subdirectory) .i need for each filename the line found (for example : filename1: line1 founded... filename2:

line2 founded... Output result in file called "logfile" if no line founded , filename not saved in logfile.

import os
word="excel"
from os.path import join
for (dirname, dirs, files) in os.walk('/batch/'):
    for filename in files:
      thefile = os.path.join(dirname,filename)
         for line in files: 
           if line.startswith(word):
                    print (line)
                    print (thefile)

Thanks


Solution

  • Your code just has minor problems: The biggest one is that you loop on filename instead of file content.

    import os
    word="excel"
    from os.path import join
    for (dirname, dirs, files) in os.walk('/batch/'):
        for filename in files:
            thefile = os.path.join(dirname, filename)
            with open(thefile) as f:
                for line in f:
                    if line.startswith(word):
                        print (line)
                        print (thefile)
    

    EDIT:

    import os
    word="excel"
    from os.path import join
    with open('log_result.txt', 'w') as log_file:
        for (dirname, dirs, files) in os.walk('/tmp/toto'):
            for filename in files:
                thefile = os.path.join(dirname, filename)
                with open(thefile) as f:
                    lines = [line for line in f if line.startswith(word)]
                if lines:
                    log_file.write("File {}:\n".format(thefile))
                    log_file.writelines(lines)