a Python script to format plain text to markdown title
iterator

There is no need for the intermediate list, just iterate over the text file line per line, and write the parsed line to the output file

variable name

f_name those 3 characters will not make writing or executing the code any slower, but writing it in full can help you understand the code later one

re.compile

You can compile the regular expression

For extra points, you can also name the groups:

re_pattern_chapter = re.compile(r"^(?P&lt;chapter&gt;\d{1,2})(?P&lt;text&gt; +.*?)")
re_pattern_out = r"# chapter(?P=chapter):(?P=text)"




import re

file_name_in = "data_multi_lines.txt"
file_name_out = "your_file.md"

re_pattern_chapter = re.compile(r"^(?P&lt;chapter&gt;\d{1,2})(?P&lt;text&gt; +.*?)")
re_pattern_out = r"# chapter(?P=chapter):(?P=text)"

with open(file_name_in, "r") as file_in, open(file_name_out, "w") as file_out:
    for line in file_name_in:
        line_parsed = re_pattern_chapter.sub(re_pattern_out, line)
        file_out.write(line_parsed)