Reputation: 35
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)
Upvotes: 2
Views: 1544
Reputation: 2115
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'))
Upvotes: 2
Reputation: 959
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?
Upvotes: 0