How Do I Specify New Lines on Python, When Writing on Files?
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...
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?
15 Answers
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.
The new line character is \n. It is used inside a string.
Example:
print('First line \n Second line')
where \n is the newline character.
This would yield the result:
First line
Second line
If you use Python 2, you do not use the parentheses on the print function.
You can either write in the new lines separately or within a single string, which is easier.
Example 1
Must Read
Input
line1 = "hello how are you"
line2 = "I am testing the new line escape sequence"
line3 = "this seems to work"
You can write the '\n' separately:
file.write(line1)
file.write("\n")
file.write(line2)
file.write("\n")
file.write(line3)
file.write("\n")