Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to strip newlines from each line during a file read? [duplicate]

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.

like image 609
mix Avatar asked Sep 18 '13 06:09

mix


2 Answers

You could use a list comprehension:

with open('words.txt') as f:
    words = [word.strip() for word in f]
like image 146
Tim Pietzcker Avatar answered Oct 15 '22 04:10

Tim Pietzcker


You can use map:

with open('words.txt') as f:
   words = map(str.rstrip, f)
like image 5
Ashwini Chaudhary Avatar answered Oct 15 '22 02:10

Ashwini Chaudhary