search.py 搜索文件或文件中的word

'''
Created on Jan 28, 2013

@author: changxue

@summary: to look for a file by filename within specified directory, 
            or look for some word in files
'''
import os
import sys
def search_file(key, scope):
    for parent, dirs, files in os.walk(scope):
        if key in files:
            print parent, key

def search_content(key, scope):                    
    for parent, dirs, files in os.walk(scope):
        for f in files:
            file_path = os.path.join(parent, f)
            count = 0
            with open(file_path, 'r') as fp:
                content = fp.readlines()
            for line in content:
                count += 1
                if line.find(key) != -1:
                    print "%s line number: %d" % (file_path, count)
    
if __name__ == '__main__':
    usage = """Usage:
    \t search -f|-c|-all key scope
    \t -f: search file in scope
    \t -c: search content in files of scope
    """
    if len(sys.argv) < 4:
        print usage
        sys.exit()
    
    key = sys.argv[2]
    scope = sys.argv[3]
    if sys.argv[1] == '-f':
        search_file(key, scope)
    elif sys.argv[1] == '-c':
        search_content(key, scope)
    elif sys.argv[1] == '-all':
        search_file(key, scope)
        search_content(key, scope)
    else:
        print usage

 

转载于:https://www.cnblogs.com/snow-backup/archive/2013/02/07/2908544.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值