简体   繁体   English

将文件读入列表并从每个列表元素中删除换行符

[英]Reading a file into a list and strip the newline from each list element

Im trying to read a text file contents into a list and then strip the newline from list element.我试图将文本文件内容读入列表,然后从列表元素中删除换行符。 however, i am receiving the incorrect output.但是,我收到不正确的 output。

infile = open('kennedy.txt','r')
line1 = infile.readline()
line2 = infile.readline() 
line3 = infile.readline() 
line4 = infile.readline() 
line5 = infile.readline() 
line6 = infile.readline() 

strip跳闸

line1 = line1.rstrip('\n')
line2 = line2.rstrip('\n')
line3 = line3.rstrip('\n')
line4 = line4.rstrip('\n')
line5 = line5.rstrip('\n')
line6 = line6.rstrip('\n')

My expected output is:我预期的 output 是:

We observe today not a victory
of party but a celebration
of freedom symbolizing an end
as well as a beginning
signifying renewal as well
as change

False
Error reading the file: no_kennedy.txt

[Errno 2] No such file or directory: 'no_kennedy.txt'
True

but my actual output is:但我实际的 output 是:

false

false

ive been reviewing my notes still dont know why its not giving me the proper output.我一直在查看我的笔记仍然不知道为什么它没有给我正确的 output。

Typically, to read the content of a file you can as follows.通常,要读取文件的内容,您可以如下所示。

SEPARATOR = "\n"

with open('kennedy.txt','r') as f:
    content = [line.strip() for line in f]

Reading line-by-line as you did is not advisable, given that generally you don't know how many lines a files as不建议像您那样逐行阅读,因为通常您不知道一个文件有多少行

With this, you have a list with all the lines already stripped from trailing/leading spaces.有了这个,您就有了一个列表,其中所有行都已从尾随/前导空格中删除。 The you can decide if you want output them line by line:您可以逐行决定是否需要 output 它们:

for line in content:
    print(line)

or join in a monolitic text, using a separator, for example或加入一个单一的文本,使用分隔符,例如

joined_content = SEPARATOR.join(content)
print(joined_content)

VERY IMPORTANT : in any case, your file is kennedy.txt , not no_kennedy.txt - which one exists in your directory?非常重要:无论如何,您的文件是kennedy.txt ,而不是no_kennedy.txt - 您的目录中存在哪一个?

First, make sure you use the same file.首先,确保使用相同的文件。 In the code, you used 'kennedy.txt', but the error is throwing 'no_kennedy.txt'.在代码中,您使用了“kennedy.txt”,但错误是抛出“no_kennedy.txt”。

Try this, and see.试试这个,看看。

with open('kennedy.txt','r', encoding='utf-8') as infile:
for line in infile.readlines():
    print(line.replace(r"\n", ""))

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

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