背景:最近在看别人的代码,学习一些东西,但是被人一个项目的代码太多了。找一个函数相当的困难啊。。。
功能:在指定目录下及其子目录下的文件中查找指定的字符。输出:关键字的目录+文件名+第几行
特点:功能单一,实用
# -*- coding: GBK -*-
import os
import os.path
rootdir = r'E:\VSworkspace\Minesweeper'#指定目录
def find(s):
for parent,dirnames,filenames in os.walk(rootdir):
for filename in filenames: #遍历文件
#print 'open:'+str(os.path.join(parent,filename))
try:
f = open(os.path.join(parent,filename))
t = f.read().split('\n')
f.close()
line,c = 0,0
for i in t:
line += 1
if c>10 : break
if i.find(s)>=0:
c += 1
print 'path: '+os.path.join(parent,filename)+' line:'+str(line)
except IOError:
#print 'error : '+str(os.path.join(parent,filename))
pass
while 1==1:
s = raw_input('关键字')
if(s=="q"): break
print "find : "+s
print "<-----------------------------------------begin---------------------------------------->"
find(s)
print "<=========================================end==========================================>"

918

被折叠的 条评论
为什么被折叠?



