The will write only the last record (str2) because the write statement is outside the for
for num, line in enumerate(name, 1): if excel_word[i] in text_string1: cnt[excel_word[i]] += 1 str2="|"+excel_word[i]+" "*(20-len(excel_word[i]))+"|"+os.path.join(root, name)+" "*(200-len(os.path.join(root, name)))+"|"+str(num)+" "*(10-len(str(num)))+"|" +"\n" else: cnt[excel_word[i]]+=0 FO.write(str2)