Chinaunix首页 | 论坛 | 博客
  • 博客访问: 297890
  • 博文数量: 240
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 50
  • 用 户 组: 普通用户
  • 注册时间: 2016-08-04 18:14
文章分类

全部博文(240)

文章存档

2017年(8)

2014年(4)

2013年(15)

2012年(4)

2011年(14)

2010年(55)

2009年(140)

我的朋友

分类: Python/Ruby

2009-03-22 21:11:10

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

#!/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)

 

阅读(827) | 评论(0) | 转发(0) |
0

上一篇:shell 脚本加密

下一篇:python 基础学习

给主人留下些什么吧!~~