搜索目录中的特定字符串

cha*_*ilk 12 python directory file

我正在尝试搜索一个充满头文件的特定目录,并浏览每个头文件,如果任何文件中有一个字符串"struct",我只想让程序打印哪个文件有它.

到目前为止我有这个,但它没有正常工作,你能帮我解决一下吗:

import glob
import os
os.chdir( "C:/headers" )
for files in glob.glob( "*.h" ):
    f = open( files, 'r' )
    for line in f:
        if "struct" in line:
            print( f )
Run Code Online (Sandbox Code Playgroud)

Hai*_* Vu 13

看来你对文件名感兴趣,而不是行,所以我们可以通过阅读整个文件并搜索来加快速度:

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

使用该with构造可确保正确关闭文件.f.read()函数读取整个文件.

更新

由于原始海报声明他的代码没有打印,我建议插入调试行:

...
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
Run Code Online (Sandbox Code Playgroud)

如果你没有看到任何以'DEBUG:'开头的行,那么你的glob()返回一个空列表.这意味着你登陆了一个错误的目录.检查目录的拼写以及目录的内容.

如果您看到'DEBUG:'行,但看不到预期的输出,则您的文件可能没有任何'struct'.通过首先cd到目录检查该情况,并发出以下DOS命令:

find "struct" *.h
Run Code Online (Sandbox Code Playgroud)