YunliuStorage
YunliuStorage

Reputation: 489

Python, Read both end of the line characters [CR][LF]

For python in windows environment
I have a log file that uses [CR][LF] as end of the line indication.

But python will only read the [LF] char (\x0A) as '\n'
[CR] or'\x0d' is somehow ignored. Len() of the read string is reduced by 1 due to this.

Is there a universal/local setting somewhere I can tell python to avoid doing that?

Upvotes: 2

Views: 3715

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155506

In Python 2, open the file in binary mode to avoid line ending translation:

with open(filename, 'rb') as f:

In Python 3, binary mode does a lot more than just disable line ending translation (it also means reading bytes instead of str), so instead you use the newline keyword argument to disable line ending translation (by passing the empty string):

with open(filename, newline='') as f:

Upvotes: 8

Related Questions