import re with open("data.txt", 'r', encoding="UTF-8") as f: text = f.read() words = re.findall(r'\b\w+\b', text) print(words) sorted_words = sorted(words, key=len) with open("output.txt", "+w", encoding="UTF-8") as f: for word in sorted_words: print(word) f.write(word + "\n")