Python学习写一小程序,从某一目录下所以文件中查询某字段,并显示文件名和所在行

时间:2021-09-03 14:33:30

     初次接触闭包,开阔了新视野呀,经过学习之后,写个小程序巩固了一下,功能类型Linux下的:grep XXXXX *


#!/sur/bin/python
#---gbk---
import os
import sys
import getopt

#how use
def Usage():
	print 'closure.py usage:'
	print '-p,--path: the file path.'
	print '-m, --format: the find string format'
	print '-o, --output: input an output verb'
	print '--foo: Test option '
	print '--fre: another test option'

#return string by format
def make_filter(keep):
		def the_filter(file_name):
				file = open(file_name)
				lines=file.readlines()
				file.close()
				filter_doc= [i for i in lines if keep in i]
				return filter_doc
		return  the_filter

#get cmd 
def main(argv):
	Usage()
	try:
		opts,args=getopt.getopt(argv[1:],'p:m:',['path=','format='])
	except getopt.GetoptError,err:
		print str(err)
		Usage()
		sys.exit(2)
	filenamelist=[]
	for o,a in opts:
		if o in ('-p','--path'):
			path=a
			filelist=os.listdir(path)
			for filename in filelist:
				if os.path.isdir(filename):
					print 'dir'	
				elif os.path.isfile(filename):
					print filename
					filenamelist.append(filename)

		elif o in ('-m','--format'):
			format=a
	for f in filenamelist:
		print f,format
		filter = make_filter(format)
		filter_result = filter(f)
		for doc in filter_result:
			print f,doc.strip()

if __name__=='__main__':
	main(sys.argv)
	

注释不多,在这描述一下, 从命令行获取了参数,参数通过-X的形式输入,从参数中获得了路径和所要匹配的字符串,调用
os.listdir(path)获得路径中文件的列表,然后遍历列表中的文件,打开每个文件,搜索所要的字符串,把字符串所在行计入结果列表中,打印,OK