def openfile(pas): with open(pas, 'r', encoding='utf-8') as f: text = f.readlines() return text def writefile(pas,s): with open(pas, 'a', encoding='utf-8') as f: f.write(s) a = openfile('D:\python\KPI\est.txt') for i in a: if '小明' in i: writefile('D:\python\KPI\est2.txt', i)