Basic

Line endings

The ending between lines is data, not decoration. Two machines can disagree about it, and that disagreement shows up as broken parsing.

What you will see

2

About 1 min of reading

Try It

Check endings in text.

1

Unix style shown.

print(repr("a\nb"))

Before you run it, say out loud what it will print. Then open the answer.

What it prints
'a\nb'
2

Windows style shown.

print(repr("a\r\nb"))

Before you run it, say out loud what it will print. Then open the answer.

What it prints
'a\r\nb'
3

Rows across both styles.

text = "a\r\nb\nc" print(len(text.splitlines()))

Before you run it, say out loud what it will print. Then open the answer.

What it prints
3
4

Endings counted.

text = "a\nb\nc" print(text.count("\n"))

Before you run it, say out loud what it will print. Then open the answer.

What it prints
2

Data Flow

Line endings are bytes in the file. Unix uses one newline, windows uses carriage return plus newline, and readers must handle both.
1 write the ending
↓
2 store the bytes
↓
3 read with splitlines
↓
4 keep one style
Line by line

Read the first example one line at a time. A line that prints shows what appears on screen; the rest set things up quietly.

print(repr("a\nb")) 'a\nb'
Why this works
The ending is stored

A file holds the ending bytes you wrote. Nothing converts them for you, so a mixed file is a mixed file.

Read tolerant, write plain

Read with splitlines so either style works, and write one style you state. That combination survives a move between machines.

Examples

Two endings

print(repr("a\nb"))
print(repr("a\r\nb"))

One newline is unix style. Carriage return plus newline is windows style. Both are real files.

Split on either

text = "a\r\nb\nc"
print(len(text.splitlines()))

splitlines handles both styles. Splitting on a bare newline leaves a stray character.

The stray character

text = "a\r\nb"
parts = text.split("\n")
print(repr(parts[0]))

Splitting on newline only leaves the carriage return stuck to the first part.

Write with one style

out = "\n".join(["a", "b"])
print(repr(out))

Build with newline and write in binary or name the ending. Then the file is predictable.

Count the endings

text = "a\nb\nc"
print(text.count("\n"))

Two endings for three lines. The last line may have none, which is legal.

A file with no ending

text = "a"
print(len(text.splitlines()))

One line, no ending. A reader that demands an ending calls this truncated.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Encoding and bytes
Previous Lesson
Encoding and bytes
Next Lesson
Paths and folders
Paths and folders →