-1

Say I have a string str="abc\n\ndef" and I want to write it to a file in a single line as it is. I use file.write(str), however, the new lines will be expanded and the file will be something like

abc


def

Is there a way I could write it into a single line?

John M.
  • 825
  • 1
  • 10
  • 22
  • Well you did use 2 `\n`'s. – Have a nice day Mar 17 '21 at 18:40
  • see https://stackoverflow.com/questions/41063524/write-escaped-character-to-file-so-that-the-character-is-visible – Shivam Jha Mar 17 '21 at 18:41
  • You know that `"abc\n\ndef"` is the representation of the string and not the content? That string has 6 characters: a, b, c, d, e, f and 2 newline characters. There is no backslash and no character "n" in the string. So "write as it is" is **not** what you want. – Matthias Mar 17 '21 at 19:50

3 Answers3

0

Use r-strings if you don't want \n to turn into newline:

str=r"abc\n\ndef"
file.write(str)
md2perpe
  • 3,372
  • 2
  • 18
  • 22
0

I assume you mean you want a file with "abc\n\ndef". If so you can by escaping the escape character: str="abc\\n\\ndef"

0
str="abc\n\ndef"
file.write(repr(str))

this prints 'abc\n\ndef'

EDIT

if you do not want the ' ', use:

str="abc\n\ndef"
file.write(str.replace("\n", "\\n"))
Jelle
  • 198
  • 9