How do I specify new lines in a string in order to write multiple lines to a file?
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Industries in Orbit Looping
--
Chapters
00:00 Question
00:22 Accepted answer (Score 471)
00:58 Answer 2 (Score 117)
01:25 Answer 3 (Score 31)
01:46 Answer 4 (Score 29)
02:43 Thank you
--
Full question
https://stackoverflow.com/questions/1149...
Accepted answer links:
[os]: http://docs.python.org/library/os.html
--
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.
"""))