import re F=open('nptmdtrj1.gro','r') A=open('Trial2.txt','w') with open ('nptmdtrj1.gro') as F: for x in F: line=x.strip() # if line.startswith ("Generated by"): # A.write(x) if re.search('OW', line): A.write(x) A.close() F.close()