Jerry
Jerry

Reputation: 15

How can I write '\n' into a text file with python?

I want to write a '\n' into a text file through python but it registers as a new line.

f=open(newpath + '/rewrite.py', 'w')
f.write('''#!/usr/bin/python
print "Content-type: text/html\n"''')

I tried to go around it and just avoid the '\n' but I keep getting internal server errors.

Upvotes: 1

Views: 7014

Answers (4)

user3273866
user3273866

Reputation: 604

>>> f=open( './rewrite.py', 'w')
>>> f.write('''#!/usr/bin/python
... print "Content-type: text/html\\n"''')
>>> f.close()

~$ cat rewrite.py
#!/usr/bin/python
print "Content-type: text/html\n"

Upvotes: 0

Dan Lenski
Dan Lenski

Reputation: 79762

Two ways:

  • Put a double backslash in a string to escape it, e.g. "\\" or '''\\''' for the triple-quotes you're using.
  • The other is to put r in front of the quotes to make it a "raw" string literal that ignores backslashes, e.g. r"\" or r'''\'''

Wikipedia has a nice illustration of Python raw string literals.

Upvotes: 1

Kamikai
Kamikai

Reputation: 185

You can encode backslashes by escaping it with a backslash, "\\n" will actually put a \ and then an n into the string, whereas "\n" encodes the actual newline character.

Upvotes: 7

omz
omz

Reputation: 53551

Use a double backslash to escape it.

Upvotes: 2

Related Questions