在目录中搜索特定字符串

13 投票
2 回答
31455 浏览
提问于 2025-04-17 14:49

我想在一个特定的文件夹里搜索一些头文件,然后查看每个头文件,如果里面有“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 )

2 个回答

1

我在这边测试的时候是可以正常工作的:

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

确保你打印的是 f.name,否则你打印的是文件对象,而不是文件的名字。

14

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

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

使用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

如果你没有看到任何以'DEBUG:'开头的行,那说明你的glob()函数返回了一个空列表。这意味着你可能进入了错误的目录。检查一下你的目录拼写,以及目录中的内容。

如果你看到了'DEBUG:'的行,但没有看到预期的输出,可能是你的文件里没有任何'struct'。你可以先进入那个目录,然后执行以下DOS命令来检查:

find "struct" *.h

撰写回答