利用python实现关键词搜索文件功能。输入信息包括需要搜索的文件夹路径和文件关键词,输出结果为文件的绝对路径,如下给出三个函数,和程序执行用法:
#-*- coding:utf-8 -*- #===============================# #Brief : search file by keyword #Date : 2022-1-1 #Support : youcunwang1@163.com #===============================#
#=========================# # import part #=========================# import os,sys # def search_file(ipath,keyword): # get ./ if not os.path.isdir(ipath): ipath = os.getcwd() # file walk x = os.walk(ipath) for a, b, c in x: for i in c: if keyword in i: key_path = os.path.join(a, i) key_path = os.path.abspath(key_path) print(' file get || abspath : %s' %(key_path)) # def usage(): print("python xx.py <-ipath path> <-key keyword> ") sys.exit(1) # def main(): argc = len(sys.argv) if argc < 5: usage() # for i,j in enumerate(sys.argv): # if j in ['-ipath']: ipath = sys.argv[i+1] # elif j in ['-key']: key = sys.argv[i+1] # elif j in ['-h']: usage() # search_file(ipath,key) # # Entry main()
如下给出简单示例:输入路径为当前所在路径,关键词为py,
python 03_search_key.py -ipath ./ -key py
输出结果为: