Skyvell
Skyvell

Reputation: 53

Why is \n included when reading files? Python

As the title states: Why is \n included when reading files?

I found a lot of information about how to remove it - but no information about why it is there in the first place.

Upvotes: 1

Views: 637

Answers (2)

jberrio
jberrio

Reputation: 1124

Adding to what others have answered - Python could have been designed to discard it when reading each line. But then, if you rewrite each line to a new file, you would have to add it; otherwise it would write all the lines it read into a single straight line.

Keeping it (as read from data files) maintains the integrity of the original data and allows you to manipulate it from its original condition.

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 117876

The '\n' character is read because it exists in the file, simple as that. If there were no line breaks or carriage returns, the text file would render as a single line of text.

For example, if you open a notepad application and see

this is a sentence
that wraps over

Then that explicitly contains the characters

this is a sentence\nthat wraps over

Upvotes: 5

Related Questions