简体   繁体   English

Python,读取行尾两个字符[CR] [LF]

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

For python in windows environment 对于Windows环境中的python
I have a log file that uses [CR][LF] as end of the line indication. 我有一个使用[CR] [LF]作为行尾指示的日志文件。

But python will only read the [LF] char (\\x0A) as '\\n' 但是python只会将[LF] char(\\ x0A)读为'\\ n'
[CR] or'\\x0d' is somehow ignored. [CR]或'\\ x0d'被忽略。 Len() of the read string is reduced by 1 due to this. 因此,读取字符串的Len()减少1。

Is there a universal/local setting somewhere I can tell python to avoid doing that? 我可以告诉python避免某个地方的通用/本地设置吗?

In Python 2, open the file in binary mode to avoid line ending translation: 在Python 2中,以二进制模式open文件以避免行尾翻译:

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): 在Python 3中,二进制模式不仅仅是禁用行尾翻译(这还意味着读取bytes而不是str ),它的功能还很多,因此,您可以使用newline关键字参数禁用行尾翻译(通过传递空字符串):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM