Python开发文件搜索脚本

#!/usr/bin/env python
#coding:utf-8

import os, sys

#判断位置参数
argv_num = len(sys.argv)
if argv_num != 3:
    print ("请至少输入2位参数:")
    print ("########################################")
    print ("EXample: python %s \033[1;31mfilename file_path\033[0m" % sys.argv[0])
    print ("########################################")
    exit()

def search(root_dir, searc):

    try:

        #获取搜索路径的整个列表目录及文件名 
        for (abs_path, dirs, files) in os.walk(root_dir):
            for filename in files:
                if searc in filename:

                    #搜索文件名的索引位置变量
                    searc_changdu = len(searc)
                    find_qian_num = filename.find(searc)
                    find_zongchang_num = searc_changdu + find_qian_num

                    #列表分片前段高亮显示变量
                    qian_1 = filename[:searc_changdu]
                    hou_1 = filename[searc_changdu:]

                    #列表分片中段高亮显示变量
                    qian_2 = filename[:find_qian_num]
                    hou_2 = filename[find_qian_num:find_zongchang_num]

                    #列表分片后段高亮显示变量
                    zhong = filename[find_qian_num:find_zongchang_num]   
                    hou_3 = filename[find_zongchang_num:]

                    #绝对路径及文件名高亮输出
                    if find_qian_num == 0:
                        print ("%s/\033[1;31m%s\033[0m%s" % (abs_path,qian_1,hou_1))
                    elif find_zongchang_num == len(filename):
                        print ("%s/%s\033[1;31m%s\033[0m" %  (abs_path,qian_2,hou_2))
                    else:
                        print ("%s/%s\033[1;31m%s\033[0m%s" %  (abs_path,qian_2,zhong,hou_3))

    #用户中断执行(通常是输入^C)
    except KeyboardInterrupt, e:
        print ("中断执行")

search(sys.argv[2], sys.argv[1])

执行效果展示

转载于:https://blog.51cto.com/yht1990/2108640

你可能感兴趣的:(Python开发文件搜索脚本)