python - '\n' == 'posix' , '\r\n' == 'nt' (python) 对吗?

标签 python posix carriage-return linefeed nt

我正在编写一个 python(2.7) 脚本,它编写一个文件并且必须在 linux、windows 和可能的 osx 上运行。 不幸的是,由于兼容性问题,我必须在 Windows 样式中使用回车和换行。 如果我假设这样可以吗:

str = someFunc.returnA_longText()
with open('file','w') as f:
    if os.name == 'posix':
        f.write(str.replace('\n','\r\n'))
    elif os.name == 'nt'
        f.write(str)    
    

我必须考虑其他人吗? os.name 还有其他选择('posix'、'nt'、'os2'、'ce'、'java'、'riscos')。我应该改用平台模块吗?

更新 1:

  1. 目标是在任何操作系统中使用 '\r\n'。

  2. 我正在接收来自

    的 str

    str = etree.tostring(root, pretty_print=True, xml_declaration=True, encoding='UTF-8')

我不是在读文件。
3. 我的错,我应该改为检查 os.linesep 吗?

最佳答案

Python 文件对象可以为您处理。默认情况下,写入文本模式文件会将 \n 行结尾转换为本地平台,但您可以覆盖此行为。

请参阅 open() function documentation 中的 newline 选项:

newline controls how universal newlines mode works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows:

  • When reading input from the stream, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. 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.
  • When writing output to the stream, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '' or '\n', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string.

(以上适用于 Python 3,Python 2 有 similar behaviour ,如果需要,io.open() 为您提供 Python 3 I/O 选项)。

如果需要强制写入行尾,请设置 newline 选项:

with open('file', 'w', newline='\r\n') as f:

在 Python 2 中,您必须以二进制模式打开文件:

with open('file', 'wb') as f:
    # write `\r\n` line separators, no translation takes place

或使用 io.open() 并写入 Unicode 文本:

import io

with io.open('file', 'w', newline='\r\n', encoding='utf8') as f:
     f.write(str.decode('utf8'))

(但要选择适当的编码;即使在 Python 3 中也明确指定编解码器始终是个好主意)。

您始终可以使用 os.linesep constant如果您的程序需要知道当前平台的适当行分隔符。

关于python - '\n' == 'posix' , '\r\n' == 'nt' (python) 对吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40972693/

相关文章:

python - 如何在 Python 中解析 Linux 终端错误消息?

newline - Web 表单中的换行符是否有标准?

python - Django:不使用runserver让服务器继续运行

python - 搜索文件并从行中返回所需字段的最佳方法

c++ - 在同一循环中集成 pthread_create() 和 pthread_join()

shell - 颠倒行序(标题除外)

shell - `ps` 命令的可移植性如何?

git - 为什么 .gitattributes 不会覆盖 Linux 上的 core.autocrlf 配置?

如果该行包含空格,C 中的回车不能正常工作

python - Pandas 中两个特定日期时间范围之间出现的数字