Search directory for specific string

后端 未结 2 2019
攒了一身酷
攒了一身酷 2021-02-19 11:47

I\'m trying to search through a specific directory full of header files, and look through each header file, and if any file has a string \"struct\" in it, I just want the progra

相关标签:
2条回答
  • 2021-02-19 11:57

    This works when I test it on my end:

    for files in glob.glob( "*.h" ):
        f = open( files, 'r' )
        file_contents = f.read()
        if "struct" in file_contents:
                print f.name
        f.close()
    

    Make sure you print f.name, otherwise you're printing the file object, and not the name of the file itself.

    0 讨论(0)
  • 2021-02-19 12:10

    It seems you are interested in the file name, not the line, so we can speed thing up by reading the whole file and search:

    ...
    for file in glob.glob('*.h'):
        with open(file) as f:
            contents = f.read()
        if 'struct' in contents:
            print file
    

    Using the with construct ensures the file to be closed properly. The f.read() function reads the whole file.

    Update

    Since the original poster stated that his code was not printing, I suggest to insert a debugging line:

    ...
    for file in glob.glob('*.h'):
        print 'DEBUG: file=>{0}<'.format(file)
        with open(file) as f:
            contents = f.read()
        if 'struct' in contents:
            print file
    

    If you don't see any line that starts with 'DEBUG:', then your glob() returned an empty list. That means you landed in a wrong directory. Check the spelling for your directory, along with the directory's contents.

    If you see the 'DEBUG:' lines, but don't see the intended output, your files might not have any 'struct' in in. Check for that case by first cd to the directory, and issue the following DOS command:

    find "struct" *.h
    
    0 讨论(0)
提交回复
热议问题