I'm reading lines from a file that contains one[*] word/line, such as:
dog
cat
person
tree
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.
You could use a list comprehension:
with open('words.txt') as f:
words = [word.strip() for word in f]
You can use map
:
with open('words.txt') as f:
words = map(str.rstrip, f)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With