如何在读取文件期间从每一行中删除换行符? [英] How to strip newlines from each line during a file read?
问题描述
我正在从包含一个[*]单词/行的文件中读取行,例如:
I'm reading lines from a file that contains one[*] word/line, such as:
dog
cat
person
tree
每个单词还包含换行符\n
字符.我想将它们读入列表并丢弃换行符.我设计的方法是使用readlines()
进行读取,然后将列表处理为strip()
换行符:
Each of these words also contains a newline \n
character. I want to read them into a list and throw away the newlines. The way I've devised is to read with readlines()
and then process the list to strip()
the newlines:
with open('words.txt') as f:
words = f.readlines()
for index, word in enumerate(words):
words[index] = word.strip()
这很好,但是我不禁想到有一种更有效的方法,可以在读取过程中删除换行符.但是我找不到办法.有没有更有效的方法(同时还考虑了可读性等)
This works fine, but I can't help thinking there's a more efficient way to do this, to strip the newlines during the read process. But I can't find a way. Is there something more efficient (while also considering readability, etc.)
[*]更新:我应该提到有些行可能包含多个单词,但是在那些情况下,一行中的很多单词应该放在一个列表项中.到目前为止,两个答案都可以解决此问题(我自己的代码也可以),但我想提一提.
[*] UPDATE: I should have mentioned that some lines may contain more than one word, and in those cases however many words are on a line should go into a single list item. Both answers so far handle this (as does my own code), but I wanted to mention it.
推荐答案
您可以使用列表理解:
with open('words.txt') as f:
words = [word.strip() for word in f]
这篇关于如何在读取文件期间从每一行中删除换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!