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

     初次接触闭包,开阔了新视野呀,经过学习之后,写个小程序巩固了一下,功能类型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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值