How do I specify new lines on Python, when writing on files?
Solution 1:
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.
Solution 2:
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.
Solution 3:
You can either write in the new lines separately or within a single string, which is easier.
Example 1
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")
Output
hello how are you
I am testing the new line escape sequence
this seems to work
Example 2
Input
As others have pointed out in the previous answers, place the \n at the relevant points in your string:
line = "hello how are you\nI am testing the new line escape sequence\nthis seems to work"
file.write(line)
Output
hello how are you
I am testing the new line escape sequence
this seems to work
Solution 4:
Platform independent line breaker: Linux,windows & IOS
import os
keyword = 'physical'+ os.linesep + 'distancing'
print(keyword)
Output:
physical
distancing
Solution 5:
EDIT: I am older and wiser now. Here is a more readable solution that will work correctly even if you aren't at top level indentation (e.g. in a function definition).
import textwrap
file.write(textwrap.dedent("""
Life's but a walking shadow, a poor player
That struts and frets his hour upon the stage
And then is heard no more: it is a tale
Told by an idiot, full of sound and fury,
Signifying nothing.
"""))
original answer
If you are entering several lines of text at once, I find this to be the most readable format.
file.write("\
Life's but a walking shadow, a poor player\n\
That struts and frets his hour upon the stage\n\
And then is heard no more: it is a tale\n\
Told by an idiot, full of sound and fury,\n\
Signifying nothing.\n\
")
The \ at the end of each line escapes the new line (which would cause an error).