I just noticed that the universal newline feature of file operations seems to be on its way out.
The documentation for Python 3.5 open
's mode
parameter indicates that it's deprecated:
'U'
universal newlines mode (deprecated)
At least as far back as Python 3.2, open
contains a similar "backwards compatibility only" warning when documenting the usage of the mode
argument:
'U'
universal newlines mode (for backwards compatibility; should not be used in new code)
Even in Python 2.7, a similar warning is placed in the documentation of io.open
.
What's the reason for this?
2 Answers 2
The open()
function in the Python 3 library has a newline
argument. Setting it to None
enables universal newlines. This is the accepted way to do it, rendering the mode='U'
argument redundant.
Use newline=None
to enable universal newlines mode (this is the default).
-
6Looks like I misunderstood. I read it as saying that universal newlines in general were being deprecated, not just the mode character. Thanks for clearing that up.jpmc26– jpmc262015年10月01日 20:21:53 +00:00Commented Oct 1, 2015 at 20:21
After stumbling across this question, I updated the documentation to be clearer about what's going on (https://github.com/python/cpython/pull/11646/files).
The confusingly cryptic table entry for 'U'
is gone, and instead there's a paragraph further down that states:
There is an additional mode character permitted,
'U'
, which no longer has any effect, and is considered deprecated. It previously enabled :term:universal newlines
in text mode, which became the default behaviour in Python 3.0. Refer to the documentation of the :ref:newline <open-newline-parameter>
parameter for further details.
Note: as of Python 3.11, this paragraph is no longer present in the docs, as the long-deprecated option has now been removed entirely.
-
3An answer that references an upstream patch in the docs by the author - the right way for stackexchanges to work. Kudos @ncoghlan.qneill– qneill2021年02月04日 18:56:34 +00:00Commented Feb 4, 2021 at 18:56
-
@ncoghlan It's still confusing and some what untechnical. In which mode are the newlines kept, if I need them to roundtrip? Does this mean, I need to read the text file as binary, if I want to keep the original newlines, then UTF-8 decode to a string, and then write it back as binary? IMHO it's too restrictive. Other script languages have ways to DWIM (Do What I Mean).Helmut Wollmersdorfer– Helmut Wollmersdorfer2022年12月06日 14:10:43 +00:00Commented Dec 6, 2022 at 14:10
-
@HelmutWollmersdorfer
newline=''
is likely the option you want: stackoverflow.com/questions/5144382/…ncoghlan– ncoghlan2022年12月16日 04:04:03 +00:00Commented Dec 16, 2022 at 4:04
U
flag toopen
'smode
parameter is deprecated in Python 3.3 and removed entirely in Python 3.11