import os file = open("blabla.txt",'r') data = file.readlines() for line in data: word = line.split() file.close() result = [i for i in word if i.startswith('d')] result2 = [i for i in word if i.startswith('D')] result0 = result + result2 file2 = open("blabla_d.txt",'w') for i in range(len(result0)): file2.write(result0[i]+"\n") print(str(i+1)+" words were recorded to "+os.path.realpath(file2.name)) file2.close()