Python 读取 txt 文件中的 \n 和 \r
Python to read \n and \r in a txt file
我刚刚使用 Notepad++ 编辑了一个 txt 文件 (file0.txt),只需单击 Enter 键。就是这样,只有一行。
我查看了几个与 \r 和 \n 之间的区别相关的 Whosebug questions/answers。我已经确认,即使在 Notepad++ 文本编辑器 window 上,在 Windows OS 上,单击 Enter 键也会引入两个 ASCII 字符,CRLF(\r\n) .
那么,为什么当我使用此 Python 3.4 代码打印先前编辑的文件的行时:
ffile=open('file0.txt')
for line in ffile:
print(ascii(line))
我明白了吗
'\n'
在终端而不是:
'\r\n'
幕后花絮:
ffile=open('file0.txt')
open
创建 TextIOWrapper
的实例
>>> print(ffile)
<_io.TextIOWrapper name='/tmp/asdf' mode='r' encoding='UTF-8'>
来自TextIOWrapper的文档:
Lines in the input can end in '\n', '\r', or '\r\n', and these are
translated into '\n' before being returned to the caller
我刚刚使用 Notepad++ 编辑了一个 txt 文件 (file0.txt),只需单击 Enter 键。就是这样,只有一行。
我查看了几个与 \r 和 \n 之间的区别相关的 Whosebug questions/answers。我已经确认,即使在 Notepad++ 文本编辑器 window 上,在 Windows OS 上,单击 Enter 键也会引入两个 ASCII 字符,CRLF(\r\n) .
那么,为什么当我使用此 Python 3.4 代码打印先前编辑的文件的行时:
ffile=open('file0.txt')
for line in ffile:
print(ascii(line))
我明白了吗
'\n'
在终端而不是:
'\r\n'
幕后花絮:
ffile=open('file0.txt')
open
创建 TextIOWrapper
>>> print(ffile)
<_io.TextIOWrapper name='/tmp/asdf' mode='r' encoding='UTF-8'>
来自TextIOWrapper的文档:
Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller