在 python 中禁用从 \r\n 到 \n 的自动更改
disable the automatic change from \r\n to \n in python
我在 ubuntu 下处理一个 python3.4 脚本,我在其中输入参数文件(编码为 UTF-8),该文件是在 Windows 下生成的。我必须逐行查看文件(由 \r\n
分隔)知道 "lines" 包含一些我想保留的 '\n'
。
我的问题是 Python 在打开文件时将文件的 "\r\n"
转换为 "\n"
。我试过用不同的模式打开("r"
、"rt"
、"rU"
)。
我找到的唯一解决方案是以二进制模式而不是文本模式工作,以 "rb"
模式打开。
有没有办法不用二进制模式或正确的方法来做到这一点?
编辑:解决方案:
with open(filename, "r", newline='\r\n') as f:
将 newline
关键字参数设置为 open()
到 '\r\n'
,或者可能为空字符串:
with open(filename, 'r', encoding='utf-8', newline='\r\n') as f:
这告诉 Python 仅在 \r\n
行终止符处拆分行; \n
在输出中保持不变。如果将其设置为 ''
,\n
也被视为行终止符,但 \r\n
不会转换为 \n
.
来自open()
function documentation:
newline controls how universal newlines mode works (it only applies to text mode). It can be None
, ''
, '\n'
, '\r'
, and '\r\n'
. [...] If it is ''
, universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.
大胆强调我的。
我在 ubuntu 下处理一个 python3.4 脚本,我在其中输入参数文件(编码为 UTF-8),该文件是在 Windows 下生成的。我必须逐行查看文件(由 \r\n
分隔)知道 "lines" 包含一些我想保留的 '\n'
。
我的问题是 Python 在打开文件时将文件的 "\r\n"
转换为 "\n"
。我试过用不同的模式打开("r"
、"rt"
、"rU"
)。
我找到的唯一解决方案是以二进制模式而不是文本模式工作,以 "rb"
模式打开。
有没有办法不用二进制模式或正确的方法来做到这一点?
编辑:解决方案:
with open(filename, "r", newline='\r\n') as f:
将 newline
关键字参数设置为 open()
到 '\r\n'
,或者可能为空字符串:
with open(filename, 'r', encoding='utf-8', newline='\r\n') as f:
这告诉 Python 仅在 \r\n
行终止符处拆分行; \n
在输出中保持不变。如果将其设置为 ''
,\n
也被视为行终止符,但 \r\n
不会转换为 \n
.
来自open()
function documentation:
newline controls how universal newlines mode works (it only applies to text mode). It can be
None
,''
,'\n'
,'\r'
, and'\r\n'
. [...] If it is''
, universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.
大胆强调我的。