gpt4 book ai didi

python - Python写换行时避免写回车 '\r'

转载 作者:太空狗 更新时间:2023-10-29 20:51:25 24 4
gpt4 key购买 nike

如果考虑到 carriage return =\rline feed =\n

Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> '{:02x}'.format(ord('\n'))
'0a'
>>> '{:02x}'.format(ord('\r'))
'0d'

如何在使用 open('filename','w').write('text\n') 时避免写回车?

在交互模式下你可以这样做:

>>> open('filename','w').write('text\n')
5
>>> for c in open('filename','r').read():
... print('{:02x}'.format(ord(c)))
...
74
65
78
74
0a

这表明只写了换行符,因此它应该是 5 个字节长。

-rw-r--r-- 1 djuric 197121        6 Jul 15 21:00 filename
^

实际上是6个字节长。现在这可能是一个“Windows 东西”,但是当你在 Notepad++ 中打开文件时,你打开 View > Show Symbols > Show All Characters 你可以在那里看到回车符。

按 CTRL+H 并使用扩展搜索模式将\r 替换为空后,只剩下换行符。保存文件后,文件中只有换行符,文件长度为5字节。

-rw-r--r-- 1 djuric 197121    5 Jul 15 20:58 filename1
^

那为什么Notepad++可以保存无回车换行,而python不能呢?

最佳答案

您可以通过在打开文本文件时将 '' 传递给 newline 参数来做到这一点。

f = open('test.txt', 'w', newline='')
f.write('Only LF\n')
f.write('CR + LF\r\n')
f.write('Only CR\r')
f.write('Nothing')
f.close()

docs 中所述:

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.

newline 的默认值为 None,通过指定 '',您将强制 Python 编写换行符(\n\r) 而不翻译它。

关于python - Python写换行时避免写回车 '\r',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38404827/

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