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


How can I indicate a newline in a string in Python, so that I can write multiple lines to a text file?

Asked By: FabianCook



The same way with 'n', though you’d probably not need the 'r'. Is there a reason you have it in your Java version? If you do need/want it, you can use it in the same way in Python too.

Answered By: Levon

In Python you can just use the new-line character, i.e. n

Answered By: mhawke

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.

Answered By: Charlie Martin

Most escape characters in string literals from Java are also valid in Python, such as “r” and “n”.

Answered By: dolaameng

The new line character is n. It is used inside a string.


    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.

Answered By: python_powered

You can either write in the new lines separately or within a single string, which is easier.

Example 1


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:



hello how are you
I am testing the new line escape sequence
this seems to work

Example 2


As others have pointed out in the previous answers, place the n at the relevant points in your string:

line = "hello how are younI am testing the new line escape sequencenthis seems to work"



hello how are you
I am testing the new line escape sequence
this seems to work
Answered By: Hom Bahrani

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
    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.
Answered By: fredcallaway

Simplest solution

If you only call print without any arguments, it will output a blank line.


You can pipe the output to a file like this (considering your example):

f = open('out.txt', 'w')
print 'First line' >> f
print >> f
print 'Second line' >> f

Not only is it OS-agnostic (without even having to use the os package), it’s also more readable than putting n within strings.


The print() function has an optional keyword argument for the end of the string, called end, which defaults to the OS’s newline character, for eg. n. So, when you’re calling print('hello'), Python is actually printing 'hello' + 'n'. Which means that when you’re calling just print without any arguments, it’s actually printing '' + 'n', which results in a newline.


Use multi-line strings.

s = """First line
    Second line
    Third line"""
f = open('out.txt', 'w')
print s >> f
Answered By: aalaap

n – simple newline character insertion works:

# Here's the test example - string with newline char:
In [36]: test_line = "Hi!!!n testing first line.. n testing second line.. n and third line....."


In [37]: print(test_line)

 testing first line..
 testing second line..
 and third line.....

Answered By: Surya

n separates the lines of a string. In the following example, I keep writing the records in a loop. Each record is separated by n.

f = open("jsonFile.txt", "w")

for row_index in range(2, sheet.nrows):

  mydict1 = {
    "PowerMeterId" : row_index + 1,
    "Service": "Electricity",
    "Building": "JTC FoodHub",
    "Floor": str(Floor),
    "Location": Location,
    "ReportType": "Electricity",
    "System": System,
    "SubSystem": "",
    "Incomer": "",
    "Category": "",
    "DisplayName": DisplayName,
    "Description": Description,
    "Tag": tag,
    "IsActive": 1,
    "DataProviderType": int(0),
    "DataTable": ""
  mydict1.pop("_id", None)
  f.write(str(mydict1) + 'n')


Platform-independent line breaker: Linux, Windows, and iOS

import os
keyword = 'physical'+ os.linesep + 'distancing'


Answered By: Bandham Manikanta

As mentioned in other answers: "The new line character is n. It is used inside a string".

I found the most simple and readable way is to use the "format" function, using nl as the name for a new line, and break the string you want to print to the exact format you going to print it:

Python 2:


Python 3:

nl = "n"

That will output:


This way it performs the task, and also gives high readability of the code 🙂

Answered By: Rea Haas

It is worth noting that when you inspect a string using the interactive Python shell or a Jupyter Notebook, the n and other backslashed strings like t are rendered literally:

>>> gotcha = 'Here is some random message...'
>>> gotcha += 'nAdditional content:nt{}'.format('Yet even more great stuff!')
>>> gotcha
'Here is some random message...nAdditional content:ntYet even more great stuff!'

The newlines, tabs, and other special non-printed characters are rendered as whitespace only when printed, or written to a file:

>>> print('{}'.format(gotcha))
Here is some random message...
Additional content:
    Yet even more great stuff!
Answered By: Trutane

In Python 3, the language takes care of encoding newlines for you in the platform’s native representation. That means rn on Windows, and just n on grown-up systems.

Even on U*x systems, reading a file with Windows line endings in text mode returns correct results for text, i.e. any r characters before the n characters are silently dropped.

If you need total control over the bytes in the file, you can use binary mode. Then every byte corresponds exactly to one byte, and Python performs no translation.

>>> # Write a file with different line endings, using binary mode for full control
>>> with open('/tmp/demo.txt', 'wb') as wf:
...     wf.write(b'DOS linern')
...     wf.write(b'U*x linen')
...     wf.write(b'no line')

>>> # Read the file as text
>>> with open('/tmp/demo.txt', 'r') as text:
...     for line in text:
...         print(line, end='')
DOS line
U*x line
no line

>>> # Or more demonstrably
>>> with open('/tmp/demo.txt', 'r') as text:
...     for line in text:
...         print(repr(line))
'DOS linen'
'U*x linen'
'no line'

>>> # Back to bytes!
>>> with open('/tmp/demo.txt', 'rb') as binary:
...     for line in binary:
...         print(line)
b'DOS linern'
b'U*x linen'
b'no line'

>>> # Open in binary, but convert back to text
>>> with open('/tmp/demo.txt', 'rb') as binary:
...     for line in binary:
...         print(line.decode('utf-8'), end='')
DOS line
U*x line
no line

>>> # Or again in more detail, with repr()
>>> with open('/tmp/demo.txt', 'rb') as binary:
...     for line in binary:
...         print(repr(line.decode('utf-8')))
'DOS linern'
'U*x linen'
'no line'
Answered By: tripleee



I personally prefer this format.

Answered By: Lynne

Various equivalent methods

Using print

print already appends a newline by default!

with open("out.txt", "w") as f:
    print("First", file=f)
    print("Second", file=f)


with open("out.txt", "w") as f:
    print("FirstnSecond", file=f)

To print without automatically adding a newline, use sep="" (since sep="n" is the default):

with open("out.txt", "w") as f:
    print("FirstnSecondn", sep="", file=f)

Using f.write

For files opened in text mode:

with open("out.txt", "w") as f:

For files opened in binary mode, the files will be written without automatic translation of n to the platform-specific line terminator. To enforce the newline character for the current platform is used, use os.linesep instead of n:

with open("out.txt", "wb") as f:
    f.write("First" + os.linesep)
    f.write("Second" + os.linesep)

Output file



On Linux, the newlines will be separated by n:


On Windows, the newlines will be separated by rn:


To avoid automatic translation of n to rn for files opened in text mode, open the file using open("out.txt", "w", newline="n").

Answered By: Mateen Ulhaq
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.