[英]Why does readlines() include a \n character in my text file if it doesn't exist?
I am attempting to read a file and collect every character which includes the following: "\\n" "\\t" " " 我正在尝试读取文件并收集包括以下内容的每个字符:“ \\ n”“ \\ t”“”
My text file contains the following: 我的文本文件包含以下内容:
aaabbcddd
I intentionally left out \\n, so python should stop reading at d. 我故意省略了\\ n,因此python应该在d停止读取。
The code is as follows: 代码如下:
fname = "files.txt"
content = []
with open(fname) as f:
for each_line in f:
for each_character in each_line:
content.append(each_character)
print(content)
My output for content is: 我对内容的输出是:
['a', 'a', 'a', 'b', 'b', 'c', 'd', 'd', 'd', '\n']
It is fine if '\\n' is stored in my list if it was intentionally inserted; 如果故意将'\\ n'存储在我的列表中,那很好。 however, in this instance, I did not put '\\n'.
但是,在这种情况下,我没有输入'\\ n'。
What went wrong? 什么地方出了错?
You read a line. 您读了一行。
A line is terminated by a newline character. 行以换行符终止。 I am pretty sure that your text editor inserts that at the end of what you typed.
我很确定您的文本编辑器会在您键入的内容的末尾插入该内容。
Try adding a simple trace of what you get on input: 尝试添加关于输入内容的简单跟踪:
for each_line in f:
print(len(each_line), "|", each_line, "|")
My output: 我的输出:
10 | aaabbcddd
|
['a', 'a', 'a', 'b', 'b', 'c', 'd', 'd', 'd', '\n']
Even though I did not add a return character to the file, and it has only a single line, the editor (vi) assumes it. 尽管我没有返回字符添加到该文件,它只有一行,编辑器(六)假定它。 The input string has 9 letters and the newline.
输入的字符串包含9个字母和换行符。
Are you sure your text file does not have a newline after this string? 您确定您的文本文件在此字符串之后没有换行符吗? I've tried running your code as is, and it does not include the '\\n' in the array.
我已尝试按原样运行您的代码,并且该代码在数组中不包含“ \\ n”。 This is what is outputted:
这是输出的内容:
['a', 'a', 'a', 'b', 'b', 'c', 'd', 'd', 'd']
Sometimes a newline could be inserted accidentally in the text file and it doesn't hurt to double check. 有时可能会在文本文件中意外插入换行符,并且再次检查也无妨。
也许文本编辑器会自动保存换行符?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.