Why \n does not expand when read file but yes in built-in strings?

  • If you run

    tmpl = "This is the first line\n And this is the second line"
    print("tmpl)
    

    you get

     This is the first line
     And this is the second line
    

    So you get a new line expanded.

  • But if you write in a file, you will not get that:

    Put in test.tmpl:

    This is the first line\n And this is the second line
    

    and run

    with open("test.tmpl") as f:
        contents = f.read()
        print(contents)
    

    you get

    This is the first line\n And this is the second line
    

Why this behaviour? How can you get the the contents displays the same than tmpl?

>Solution :

A Python string is interpreted by the Python interpreter. The Python interpreter knows what escape characters are and how to deal with them.

When reading a text file, you get the characters as they are. A newline in a text file consists of the characters 0x0D (CR; carriage return) and/or 0x0A (LF; line feed). You get that when pressing Enter on your keyboard. If you want to consider escape characters in a text file, you need to implement that yourself.

Applied to your case:

with open("test.tmpl") as f:
    contents = f.read()
    contents = bytes(contents, "utf-8").decode("unicode_escape")
    print(contents)

Leave a Reply