How do I specify new lines on Python, when writing on files?

FabianCook picture FabianCook · Jul 16, 2012 · Viewed 1.9M times · Source

In comparison to Java (in a string), you would do something like "First Line\r\nSecond Line".

So how would you do that in Python, for purposes of writing multiple lines to a regular file?

Answer

Charlie Martin picture Charlie Martin · Jul 16, 2012

It depends on how correct you want to be. \n will usually do the job. If you really want to get it right, you look up the newline character in the os package. (It's actually called linesep.)

Note: when writing to files using the Python API, do not use the os.linesep. Just use \n; Python automatically translates that to the proper newline character for your platform.