1

I am new in Python. I have the following problem: I have a string with newline character and I want to write this string with newline character to a file. I want the new line character to be explicitly visible in the file. How can I do that please? This is my current code:

 text = "where are you going?\nI am going to the Market?"
    with open("output.txt",'w', encoding="utf-8") as output:
        output.write(text)
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
EDW
  • 25
  • 3
  • Does this answer your question? [Writing string to a file on a new line every time](https://stackoverflow.com/questions/2918362/writing-string-to-a-file-on-a-new-line-every-time) – Amit Baranes Dec 27 '19 at 19:07
  • A new line character is a newline. Do you mean a literal ``\`` followed by a ``n``? – MisterMiyagi Dec 27 '19 at 19:36
  • Does this answer your question? [Converting characters to their python escape sequences](https://stackoverflow.com/questions/5864279/converting-characters-to-their-python-escape-sequences) – MisterMiyagi Dec 27 '19 at 19:38

2 Answers2

1

Just replace the newline character with an escaped new line character

text = "where are you going?\nI am going to the Market?"
with open("output.txt",'w', encoding="utf-8") as output:
    output.write(text.replace('\n','\\n'))
prithajnath
  • 2,000
  • 14
  • 17
0

If you want the new line character to remain visible in your file without having actually a new line, just add a \ before the new line character:

text = "where are you going?\\nI am going to the market?"

print(text)
>>> where are you going?\nI am going to the market?
KrazyMax
  • 939
  • 6
  • 16