TheWaveLad
TheWaveLad

Reputation: 1016

Cannot save string to file with `\n` characters

The following code produces a file with content test\\nstring, but I need the file to contain test\nstring. I can't figure out a way to replace the \\symbol either.

s = "test\nstring"
with open('test.txt', 'w') as f:
    f.write(s)

How can I make sure that the file contains only \n instead of \\n?

Upvotes: 0

Views: 87

Answers (3)

Andrey Kostrenko
Andrey Kostrenko

Reputation: 119

The raw strings may help

s = r"test\nstring"
with open('test.txt', 'w') as f:
    f.write(s)

Upvotes: 1

Jose
Jose

Reputation: 3460

Besides of escaping and raw string, you can encode it (2 or 3) with 'string_escape':

s = "test\nstring".encode('string_escape')
with open('test.txt', 'w') as f:
    f.write(s)

Upvotes: 1

Prince Francis
Prince Francis

Reputation: 3097

use s = "test\\nstring" I tried with the following code and worked.

s = "test\\nstring"
with open('test.txt', 'w') as f:
  f.write(s)

and the test.txt file contains

    test\nstring

Upvotes: 1

Related Questions