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

Viewed 2455340

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

16 Answers

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

import os
keyword = 'physical'+ os.linesep + 'distancing'
print(keyword)

Output:

physical
distancing

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:

print("line1{nl}"
      "line2{nl}"
      "line3".format(nl="\n"))

Python 3:

nl = "\n"
print(f"line1{nl}"
      f"line2{nl}"
      f"line3")

That will output:

line1
line2
line3

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

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:\n\t{}'.format('Yet even more great stuff!')
>>> gotcha
'Here is some random message...\nAdditional content:\n\tYet 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!

In Python 3, the language takes care of encoding newlines for you in the platform's native representation. That means \r\n 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 line\r\n')
...     wf.write(b'U*x line\n')
...     wf.write(b'no line')
10
9
7

>>> # 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 line\n'
'U*x line\n'
'no line'

>>> # Back to bytes!
>>> with open('/tmp/demo.txt', 'rb') as binary:
...     for line in binary:
...         print(line)
b'DOS line\r\n'
b'U*x line\n'
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 line\r\n'
'U*x line\n'
'no line'

Use:

"{}\n{}\n{}".format(
    "line1",
    "line2",
    "line3"
)

I personally prefer this format.

\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')

f.close()

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)

Equivalently:

with open("out.txt", "w") as f:
    print("First\nSecond", 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("First\nSecond\n", sep="", file=f)

Using f.write

For files opened in text mode:

with open("out.txt", "w") as f:
    f.write("First\nSecond\n")

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

Visually:

First
Second

On Linux, the newlines will be separated by \n:

First\nSecond\n

On Windows, the newlines will be separated by \r\n:

First\r\nSecond\r\n

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

Related