在目录中查找指定的字符串
# -*- coding: cp936 -*- '''在python中查找字符串,如果文件中包含指定的字符串, 则将此字符串所在的行号和文件名称打印出来,不支持正则表达式, 演示了walk使用方法; 演示了fileinput使用方法''' import os # 使用walk来遍历目录 def processFiles(arg,dirpath,files): '''walk函数的回调函数, 查找满足条件的文件,使用fileinput对文件进行搜索, 如果查找到关键字,打印出行号和文件名称''' for f in files: fname = os.path.join(dirpath,f) if(os.path.isfile(fname)): if os.path.splitext(fname)[1] == '.py': import fileinput import sys # 使用fileinput来遍历文件,如果有Tk则将此【行号:文件名称】插入搜索结果列表框 for line in fileinput.input(fname): # 在这里使用vTextFind,查找指定的字符串 if line.find(root.vTextFind.get()) != -1: root.lbResults.insert(END,"[%d]:[%s]" % (fileinput.lineno(),fname))
def updateListbox(master): '''搜索按钮的事件处理函数, 这个函数调用walk来遍历目录,并将搜索结果插入列表框''' print master.vDirSearched.get() master.lbResults.delete(0,END) os.path.walk(master.vDirSearched.get(),processFiles,'')
from Tkinter import * root = Tk() # 创建搜索路径,并绑定变量,默认路径为当前'.' Label(root,text = 'Directory to be searched').grid(row = 0,column = 0) root.vDirSearched = StringVar() root.vDirSearched.set('.') root.etDirSearched = Entry(root,textvariable = root.vDirSearched) root.etDirSearched.grid(row = 0,column = 1)
# 创建要搜索的字符串,默认搜索为'Tk' Label(root,text = 'text to find').grid(row = 1,column = 0,stick = W) root.vTextFind = StringVar() root.vTextFind.set('Tk') root.etTextFind = Entry(root,textvariable = root.vTextFind) root.etTextFind.grid(row = 1,column = 1)
# 创建搜索按钮 root.btSearch = Button(root, text = 'Search', command = lambda arg1 = root: updateListbox(arg1) ) root.btSearch.grid(row = 2,column = 0,columnspan = 2,stick = E + W) # 创建搜索结果列表 root.lbResults = Listbox(root) root.lbResults.grid(row = 3,column = 0,columnspan = 2,stick = E + W + N + S)
root.mainloop() |