1

I have str = 'some words\n' and i want to print it to file with

with open(newfile, 'a') as the_file:
    the_file.write(str)

how can i write literally just 'some words\n' not 'some words' with enter at the end?

1
  • 1
    You have to escape the backslash as a double backslash or use a raw string: str = r'some words\n' . BTW str is a bad choice for a variable name, it will mask the built-in str type. Commented Dec 28, 2017 at 7:19

5 Answers 5

2

Please try doule back slash like str = "some words \\n" .

Sign up to request clarification or add additional context in comments.

Comments

1

You need to escape the escape character:

str = 'some words\n'
with open(newfile, 'a') as the_file:
    str = str.replace("\n","\\n")
    the_file.write(str)

1 Comment

maybe you reconsider about variable naming. Naming a variable as str will change use of str's default behaviour.
1

You can use the raw-string r'..' construct to do that, also would be nice to use the file-open constructs within the try catch blocks and close the open file descriptor once the write is complete.

try:
    str = r'some words\n'
    with open('newfile', 'a') as fd:
        fd.write(str)
        fd.close()

except IOError as e:
    print('unable to open file newfile in append mode')

Comments

0
string = "some words\n"

with open("temp.txt", "w+") as fp:

        temp = string[:-2] + r'\n'

        fp.write(temp)

Comments

0

You could use the string representation without the quotes. It will work with all escape sequences, not only the '\n':

w = "some\twords\n"
repr(w)[1:-1] # some\twords\n

However there is an issue with quotes:

w = '''single'double"quote'''
repr(w)[1:-1] # single\'double"quote

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.