1

Python's file objects can now support end of line conventions other than the one followed by the platform on which Python is running. Opening a file with the mode 'U' or 'rU' will open a file for reading in universal newline mode. All three line ending conventions will be translated to a "\n" in the strings returned by the various file methods such as read() and readline().

https://docs.python.org/2.3/whatsnew/node7.html

In Python 3, universal newlines is the default mode to open text files in. That means, when opening text files, I do not have to care about line ending conventions at all.

Do we have convenience feature like this in C#, too?

1

1 Answer 1

3

StreamReader.ReadLine does this:

A line is defined as a sequence of characters followed by a line feed ("\n"), a carriage return ("\r"), or a carriage return immediately followed by a line feed ("\r\n"). The string that is returned does not contain the terminating carriage return or line feed.

The convenience methods for reading the lines out of a file, such as File.ReadLines and File.ReadAllLines, use a StreamReader under the hood.

I don't know of any method which will read multiple lines from a file as a string, but will silently replace all line ending characters with a normalized \n however. StreamReader.ReadToEnd() doesn't manipulate the text it reads in this way.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, this is good enough for me, for iterating line by line. I don't need the "read a chunk and normalize" part of the feature at the moment.
Actually, I realized I'd need something like the chunk normalization part of the feature too, but thankfully for the whole content of the file. I'd just read it as lines, and join the lines with "\n" myself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.