- 帖子
- 16
- 精华
- 0
- 积分
- 61
- 阅读权限
- 20
- 注册时间
- 2016-2-2
- 最后登录
- 2017-5-8
|
回帖奖励 +5
@crossing先生
请帮我看看,新手鼓起勇气努力写了大半天,期待前辈指点,有任何错误,不妥,都请您指出,拜谢
#!\usr\bin\python
#-*-encoding:utf-8-*-
#author=xuqq
#下面这个程序实现的功能是:在一个文件夹,包括子文件夹中,寻找包含相关内容的文件,把这些文件罗列出来
import os,re
def search_in_path(path_original,str_targit):
targit_files = []
if (os.path.exists(path_original) and os.path.isabs(path_original)):
for root,dir,files in os.walk(path_original): #os.walk()遍历是个好东东
print root
print dir
print files
for file_obj in files:
file_whole_name = os.path.join(root,file_obj)
result = search_in_file(file_whole_name,str_targit)
if result !="":
targit_files.append(result)
else:
continue
else:
print "The path which you have input is not valid!"
print "最终包括这个内容的文件有:\n"
result_num = 0
for tar in targit_files:
print "%d\t%s" %(result_num,tar)
result_num = result_num+1
def search_in_file(file_original,str_targit):
if os.path.isfile(file_original):
fp = open(file_original,'r')
match = False
line = "file begin:"
i = 1
while line:
line = fp.readline()
#print "以下打印内容:\n" ,line
m = re.findall(str_targit,line)
#print "m = \t",m
if m !=[]:
match =True
print "在文件里找到了"
break
else:
continue
i = i+1
print "%_%"*28
print "match:\t",match
if match ==True:
print "Found it!\t"+file_original
fp.close()
print '*'*80
return file_original
else:
print "Nothing found!"
fp.close()
print '#'*80
return ""
def main():
search_in_path("C:\Python27", "xuqq")
if __name__ =='__main__':
main() |
|