Hi all,
I wanted to write the following line to the file.

sys.stdout.write("123: The metro polis\n")

But the line that was written is:

sys.stdout.write("100: The metro polis
")

How do I get the \n to be written in the text form to the? file(ie it should not be interpreted as a newline character, instead it should be printed as it is ie as "\n" only.

Any help would be greatly appreciated.

And I had extracted the "123: The metro polis" as a list item from some other string.
i concatenated the string and the list item as follows:
ll[1] --------> this is> 123: The metro polis
str = "sys.stdout.write"
Concatenation :
str += ll[1]

Dani AI

Generated

and are right for literal source-code strings: you can put an escaped backslash in a literal or write a raw literal so the source contains the two characters \ and n. The important gap is where your text actually comes from. If you extracted the text from ll[1] it may already contain a real newline character, so escaping the literal in source won't change that. Also, building a string that literally says sys.stdout.write (for example by doing str = "sys.stdout.write"; str += ll[1]) does not call the function — it just creates text. Avoid naming a variable str because it shadows the built-in.

Quick, practical checklist:

  • Inspect the value you extracted with repr() to see whether it contains '\n' (two characters) or an actual newline.
  • If it contains a real newline and you want the two-character sequence written, replace the newline with a backslash and n before writing. If you open the file in binary ('wb') you must encode the string to bytes when writing.

Example workflow you can apply:

s = ll[1]               # the extracted text
print(repr(s))          # shows escape sequences vs actual newlines
s = s.replace('\n', '\\n')    # convert actual newlines into the two characters
with open('out.txt', 'wb') as fh:
    fh.write(s.encode('utf-8'))

Other options: use repr(s) or json.dumps(s) when you want an escaped, printable representation for debugging; encode('unicode_escape') can help with non-ASCII escapes. Raw-string syntax only affects literal text in your source, not values already held in variables. For reference on literal behavior and repr(), see the Python docs on string literals and on repr() (string literals, repr).

Recommended Answers

All 2 Replies

Is this what you are trying to do?

sys.stdout.write("123: The metro polis\\n")

And there is also form of raw string:

sys.stdout.write(r"123: The metro polis\n")
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.