搜索目录中的特定字符串 [英] Search directory for specific string

查看:112
本文介绍了搜索目录中的特定字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在搜索完整的头文件的特定目录,并查看每个头文件,如果任何文件中有一个字符串struct,我只想让程序打印哪个文件。



我有这么远,但是它不能正常工作,可以帮我弄清楚:



<$ p
$ b import os
os.chdir(C:/ headers)
为glob.glob(* .h)中的文件:
f = open(files,'r')
在f中的行
如果struct在行中:
print(f)


解决方案

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

  ... 
在glob.glob('*。h '):
打开(文件)为f:
内容= f.read()
如果内容中的结构:
打印文件

构造确保文件被正确关闭。 f.read()函数读取整个文件。



更新



代码没有打印,我建议插入一个调试行:

  ... 
在glob.glob中的文件('* .h'):
打印'DEBUG:file => {0}<'。格式(文件)
打开(文件)为f:
contents = f .read()
如果内容中的结构:
打印文件

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



如果看到DEBUG:行,但没有看到预期的输出,您的文件可能没有任何'结构'在。检查的情况下,首先cd到目录,并发出以下DOS命令:

 查找struct* .h 


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.

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 )

解决方案

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

这篇关于搜索目录中的特定字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆