文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>search in linux

search in linux

时间:2010-08-31  来源:dyhfine

在指定路径中查找所有文本文件里的关键内容:  

#!/usr/bin/env python
import os, sys
listonly = False
skipexts = ['.gif', '.exe', '.pyc', '.o', '.a','.dll','.lib','.pdb','.mdb']

def visitfile(fname, searchKey):
    global fcount, vcount
    try:
        if not listonly:
            if os.path.splitext(fname)[1] in skipexts:
                pass
            elif open(fname).read().find(searchKey) != -1:
                print'%s has %s' % (fname, searchKey)
                fcount += 1
    except: pass
    vcount += 1

def visitor(args, directoryName,filesInDirectory):
    for fname in filesInDirectory:
        fpath = os.path.join(directoryName, fname)
        if not os.path.isdir(fpath):
            visitfile(fpath,args)

def searcher(startdir, searchkey):
    global fcount, vcount
    fcount = vcount = 0
    os.path.walk(startdir, visitor, searchkey)

if __name__ == '__main__':
    root=raw_input("type root directory:")
    key=raw_input("type key:")
    searcher(root,key)
    print 'Found in %d files, visited %d' % (fcount, vcount)


 

在指定路径中查找固定扩展名的文件:
 

#!/usr/bin/env python
import os

def anyTrue(predicate, sequence):
    return True in map(predicate, sequence)

def filterFiles(folder, exts):
    for fileName in os.listdir(folder):
        if os.path.isdir(folder + '/' + fileName):
            filterFiles(folder + '/' + fileName, exts)
        elif anyTrue(fileName.endswith, exts):
            print fileName

exts = ['.rmvb', '.avi', '.pmp','.tar.gz']
filterFiles('/root', exts)

  转自: http://blog.chinaunix.net/u3/93470/showart.php?id=1871923
相关阅读 更多 +
排行榜 更多 +
找茬脑洞的世界安卓版

找茬脑洞的世界安卓版

休闲益智 下载
滑板英雄跑酷2手游

滑板英雄跑酷2手游

休闲益智 下载
披萨对对看下载

披萨对对看下载

休闲益智 下载