Reputation: 399
I hope my code could write text regularly in both MacOS and Windows, so I hope this script have the function of mode U and meanwhile have the function of w+.
What am I supposed to do with the mode argument in file.open()?
Upvotes: 1
Views: 1291
Reputation: 7931
Writing in universal newline mode isn't supported. From the PEP:
There is no special support for output to file with a different newline convention, and so mode "wU" is also illegal.
and
There is no output implementation of universal newlines, Python programs are expected to handle this by themselves or write files with platform-local convention otherwise. The reason for this is that input is the difficult case, outputting different newlines to a file is already easy enough in Python.
This is actually hinted at by the error returned when you try Uw+
:
ValueError: universal newline mode can only be used with modes starting with 'r'
Note that Ur+
doesn't fail, but it also doesn't do any substitution on writing; I can do f.write('test\r\n')
on my Mac (OS X uses Unix newlines), and a Windows newline appears in my file.
edit: It appears that Python actually offers platform-specific newline output by default anyway, as long as you leave the b
off.
...The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading.
Upvotes: 2