The Python Oracle

How do I specify new lines in a string in order to write multiple lines to a file?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Popsicle Puzzles

--

Chapters
00:00 How Do I Specify New Lines In A String In Order To Write Multiple Lines To A File?
00:16 Accepted Answer Score 490
00:41 Answer 2 Score 127
01:04 Answer 3 Score 39
01:18 Answer 4 Score 31
01:55 Answer 5 Score 21
02:12 Thank you

--

Full question
https://stackoverflow.com/questions/1149...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #linebreaks #filewriting

#avk47



ACCEPTED ANSWER

Score 491


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.




ANSWER 2

Score 128


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.




ANSWER 3

Score 31


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



ANSWER 4

Score 22


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.
"""))