简体   繁体   English

Python在txt文件中读取\\ n和\\ r

[英]Python to read \n and \r in a txt file

I have just edited a txt file (file0.txt) with Notepad++ with just clicking the Enter key. 我刚刚用Enterpad ++编辑了一个txt文件(file0.txt),只需单击Enter键。 That´s it, just one line. 就是这样,只需一行。

I have reviewed several StackOverflow questions/answers that relate the differences between \\r and \\n. 我已经回顾了一些与\\ r和\\ n之间的区别有关的StackOverflow问题/答案。 I have confirmed, even visually on the Notepad++ text editor window, that on a Windows OS, a click on the Enter key introduces two ASCII characters, CRLF(\\r\\n). 我已经确认,即使是在Notepad ++文本编辑器窗口上,也已经在Windows操作系统上确认,单击Enter键会引入两个ASCII字符CRLF(\\ r \\ n)。

So, why in the world, when I print the line of the previously edited file using this Python 3.4 code: 因此,为什么在世界上,当我使用此Python 3.4代码打印先前编辑的文件的行时:

ffile=open('file0.txt')

for line in ffile:
    print(ascii(line))

do I get 我得到

'\n'

in the terminal instead of: 在终端而不是:

'\r\n'

Behind the scenes: 幕后花絮:

ffile=open('file0.txt')

open creates an instance of TextIOWrapper open创建一个TextIOWrapper实例

>>> print(ffile)                                                                                                       
<_io.TextIOWrapper name='/tmp/asdf' mode='r' encoding='UTF-8'>

From the docs of TextIOWrapper : 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 输入中的行可以以'\\ n','\\ r'或'\\ r \\ n'结尾,在返回给调用者之前,这些行会转换为'\\ n'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM