Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

  • 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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading