Search code examples
pythonfileionewlinetxt

when write "\n", why two characters are replaced?


test.txt:

12345

code:

dfh = open("test.txt", "r+")
dfh.seek(0, 0)
dfh.write("\n")
dfh.close()

output:

(empty line)
345

I expected output to be

(empty line)
2345

why "\n" replace two chracters?


Solution

  • In your situation I think you are using windows since windows uses 2 characters \r\n to get to a new line.

    Quoting from another stackoverflow post