Universal Newlines

In Python, universal newlines provide a convenient way to handle files with different newline conventions across different platforms.

When you open a file in Python with universal newlines enabled, the interpreter automatically translates all newline characters into the standard \n newline character. Whether your file uses \r, \n, or \r\n to indicate a new line, Python will treat them uniformly as \n. This feature is especially useful when dealing with text files that may originate from different operating systems, ensuring consistent behavior when reading or writing files.

The built-in open() function with the newline argument set to None—its default value—enable universal newline handling. You don’t need to do anything special to enable it.

Example

Here’s a simple example where you create a file that uses \r as its newline character and then read the file back:

Python
>>> with open("example.txt", mode="w", newline="") as file:
...     file.write("Line 1\rLine 2\rLine 3\r")
...
21

>>> with open("example.txt", mode="r", newline=None) as file:
...     for line in file:
...         print(repr(line))
...
'Line 1\n'
'Line 2\n'
'Line 3\n'

When you read the file, you’ll see that each line ends with the standard \n character. Python internally handles the newline character conversion for you.

Tutorial

Reading and Writing Files in Python (Guide)

In this tutorial, you'll learn about reading and writing files in Python. You'll cover everything from what a file is made up of to which libraries can help you along that way. You'll also take a look at some basic scenarios of file usage as well as some advanced techniques.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Jan. 7, 2025 • Reviewed by Dan Bader