Reputation: 53
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
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
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