Python 搜索特定字符串的目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14710918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:13:03  来源:igfitidea点击:

Search directory for specific string

pythonfiledirectory

提问by chakolatemilk

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 program to print which file has it.

我试图搜索一个充满头文件的特定目录,并查看每个头文件,如果任何文件中有一个字符串“struct”,我只想让程序打印哪个文件有它。

I have this so far, but it's not working correctly, can you help me figure it out:

到目前为止我有这个,但它不能正常工作,你能帮我弄清楚吗:

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 )

采纳答案by Hai Vu

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 withconstruct ensures the file to be closed properly. The f.read() function reads the whole file.

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

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.

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

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:

如果您看到“DEBUG:”行,但没有看到预期的输出,则您的文件中可能没有任何“struct”。通过首先 cd 到目录检查这种情况,然后发出以下 DOS 命令:

find "struct" *.h

回答by Nate

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.

确保你 print f.name,否则你正在打印文件对象,而不是文件本身的名称。