Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a "\n" in a text file

I'm trying to write a string \n in a text file. But the result in the text file is a newline. I know that the \n represents a newline. But in my case, I really need to see the String \n, not the newline. How can I solve this?

like image 782
DFE Avatar asked Aug 15 '11 09:08

DFE


People also ask

How do you enter a new line in a text file in Python?

The new line character in Python is \n . It is used to indicate the end of a line of text. You can print strings without adding a new line with end = <character> , which <character> is the character that will be used to separate the lines.

Does \n count as a character Java?

No, "\n" is only recognized in java in a char or string literal, in a text file it is just considered a backslash and then n.

How do you write to a text file in Python?

To write to a text file in Python, you follow these steps: First, open the text file for writing (or append) using the open() function. Second, write to the text file using the write() or writelines() method. Third, close the file using the close() method.


1 Answers

The \ character escapes the next character, as you say \n will create a newline. If you wish to output an actual \, you need to write:

"\\n"

That way the first slash escapes the second slash, generating an actual slash rather than escaping the n.

like image 57
Charles Keepax Avatar answered Oct 29 '22 21:10

Charles Keepax