【问题标题】:Why does `write_text` appear to use CRLF and not LF?为什么`write_text`似乎使用CRLF而不是LF?
【发布时间】:2021-08-04 10:38:45
【问题描述】:

假设我们在 Windows 上,我们想创建一个包含以下内容的文本文件:

hello
world

我们跑

from pathlib import Path
Path('my.txt').write_text('hello\nworld')

并在编辑器中打开新创建的my.txt。我期待它显示LF,因为我们的字符串中有\n(而不是\r\n)。令我惊讶的是,我的编辑告诉我my.txtCRLF

为什么会这样?有没有办法用write_textLF

【问题讨论】:

    标签: python windows text newline file-writing


    【解决方案1】:

    Python 3.10 (2021-10-04) 现在支持 newline 参数。所以现在你可以这样做了:

    Path('my.txt').write_text('hello\nworld', newline='\n')
    

    参考:

    Path.write_text(data, encoding=None, errors=None, newline=None)

    https://docs.python.org/3/library/pathlib.html#pathlib.Path.write_text

    补充参考:

    https://bugs.python.org/issue23706

    【讨论】:

      【解决方案2】:

      您看到的是 Python 的 newline mapping feature(请参阅链接的 open 文档中的 newline)。

      Path().write_text() 实现如下,所以你看到你不能将newline 设置为'\n'''

          def write_text(self, data, encoding=None, errors=None):
              with self.open(mode='w', encoding=encoding, errors=errors) as f:
                  return f.write(data)
      

      您需要手动设置newline

      with Path('my.txt').open('w', newline='\n') as f:
          f.write('hello\nworld')
      

      【讨论】:

      • 有没有办法将其全局设置为\n? (即就像我在 Linux 系统上一样)
      • 文档说默认使用os.linesep。也许将其设置为 os.linesep = '\n' 可以解决问题?
      • (另一种选择是以二进制形式打开文件,然后手动编码您要在其中写入的任何文本。)
      • 除非我遗漏了什么,os.linesep = '\n' 似乎没有帮助。还是谢谢你 (+1)
      猜你喜欢
      • 2022-01-22
      • 2021-08-21
      • 1970-01-01
      • 2011-06-18
      • 1970-01-01
      • 1970-01-01
      • 2015-06-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多