通用换行符模式是否应该是 Python 2.7 中 open() 的默认行为? [英] Is universal newlines mode supposed to be default behaviour for open() in Python 2.7?

查看:31
本文介绍了通用换行符模式是否应该是 Python 2.7 中 open() 的默认行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Windows 7 上运行 Python 2.7.2(64 位).我对此处记录的通用换行模式"有点困惑:http://docs.python.org/library/functions.html#open

I'm running Python 2.7.2 (64 Bit) on Windows 7. I'm a little confused about 'universal newline mode' documented here: http://docs.python.org/library/functions.html#open

从文档看来,除非在 open() 的模式参数中指定了U",否则通用换行模式"似乎不应该生效.但是我认为这是默认行为!那么文档确实具有误导性还是我遗漏了什么?

From the documentation it seems 'universal newline mode' should not be in effect unless a 'U' is specified in the mode parameter of open(). However I see that as the default behavior! So is the documentation indeed misleading or am I missing something?

f = open("c:/Temp/test.txt", "wb")
f.write("One\r\nTwo\r\nThree\r\nFour"); f.close()

f = open("c:/Temp/test.txt", "rb")
f.read(); f.close()
'One\r\nTwo\r\nThree\r\nFour'

f = open("c:/Temp/test.txt", "r")
f.read(); f.close()
'One\nTwo\nThree\nFour'

f = open("c:/Temp/test.txt", "rt")
f.read(); f.close()
'One\nTwo\nThree\nFour'

f = open("c:/Temp/test.txt", "rU")
f.read(); f.close()
'One\nTwo\nThree\nFour'

似乎r"、rt"、rU"都具有相同的行为?

Seems like "r", "rt", "rU" all have the same behavior?

推荐答案

您正在观察这一点,因为 \r\n 是 Windows 上的行终止符,所以 t> 模式将其转换为 \n.在 Unix(此处为 MacOS)上, t 不会影响 \r\n 并且没有转换.tU 的区别在于 U 转换了 \r\n\r\n 在每个平台上,而 t 是平台相关的,并且只为给定平台转换 LT.

You're observing this because \r\n is the line terminator on Windows, so the t mode converts it to \n. On Unix (MacOS here), t doesn't affect \r\n and there's no conversion. The difference between t and U is that U converts \r\n and \r to \n on every platform, while t is platform dependent and only converts LT for the given platform.

将你的测试字符串替换为"One\r\nTwo\nThree\rFour",看看U的效果.

Replace your test string to "One\r\nTwo\nThree\rFour" to see the effect of U.

这篇关于通用换行符模式是否应该是 Python 2.7 中 open() 的默认行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆