xor
xor

Reputation: 60

How can I write to a file but keep \n as it is rather than adding a new line in python?

I am creating a program that contains all my other programs however when I attempt to write to the file it prints \n as a new line rather than literally \n.

For Example:

file.write("""a=input("What would you like?\n")

Produces:

a=input("What would you like?

")

Is there any way around this?

Upvotes: 2

Views: 1659

Answers (1)

Deelaka
Deelaka

Reputation: 13721

Use the backslash \ to escape characters that otherwise have a special meaning such as the newline, backslash itself, or the quote character for example.

Therefore use:

file.write("""a=input("What would you like?\\n")""")

Or make it a raw string by adding a r in front of the string:

file.write(r"""a=input("What would you like?\n")""")

Upvotes: 3

Related Questions