在工作中遇到一个提取一个目录中所有文本文件中含有特定字符串的行,并将其写入一个文件,于是有了以下代码。
# -*- coding: utf8 -*-
import os
import sys
import glob
import time
reload(sys)
sys.setdefaultencoding('utf-8')
abspath = os.path.dirname(__file__)
sys.path.append(abspath)
if abspath=='':
os.chdir(sys.path[0])
else:
os.chdir(abspath)
search_str='你要提取的字符串' #定义要在文本文件提取的字符串
if __name__=='__main__':
stime=time.time()
fetch_list=[]
All_in_File=glob.glob(r'*.txt')
if len(All_in_File)>0:
for infile in All_in_File:
read_file_list=open(infile,'r').readlines()
one_fetch_list=[j for j in read_file_list if j.find(search_str)>0]
if len(one_fetch_list):
file_name=infile[0:-4]
fetch_list.append(file_name.center(70,'*')+'\n')
print u'从文件\t%s\t中提取到\t%d\t条含有\t%s\t的记录'%(infile,len(one_fetch_list),search_str)
fetch_list.extend(one_fetch_list)
#for t in one_fetch_list:
# fetch_list.append(t)
fetch_list.append('-'*70+'\n\n')
out_txt=open('Fetch_result.txt','w')
out_txt.writelines(fetch_list)
out_txt.close()
print 'coast time:%.2f'%(time.time()-stime,)