gpt4 book ai didi

python - U模式和w+模式下如何写文件?

转载 作者:行者123 更新时间:2023-12-01 05:56:28 24 4
gpt4 key购买 nike

我希望我的代码在MacOS和Windows下都能正常写入文本,所以我希望这个脚本具有模式U的功能,同时具有w+的功能。

我应该如何处理 file.open() 中的模式参数?

最佳答案

不支持以通用换行模式写入。来自 the PEP :

There is no special support for output to file with a different newline convention, and so mode "wU" is also illegal.

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.

这实际上是通过尝试 Uw+ 时返回的错误来暗示的:

ValueError: universal newline mode can only be used with modes starting with 'r'

请注意,Ur+ 不会失败,但它也不会对写入进行任何替换;我可以在 Mac 上执行 f.write('test\r\n')(OS X 使用 Unix 换行符),并且 Windows 换行符会出现在我的文件中。

编辑:看来Python actually offers platform-specific newline output by default anyway ,只要您将 b 关闭即可。

...The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading.

关于python - U模式和w+模式下如何写文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12361800/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com