Programming
python string list text-files
Updated Sat, 21 May 2022 04:32:57 GMT

Most pythonic way to create a list of strings from lines in a text file?


From a text file lines_of_words.txt, say

first
second
third

a list of words as strings has to be created, i.e.

list_of_strings = ['first', 'second', 'third']

This seems like an extremely trivial function, but I can't find a concise solution. My attempts are either too cumbersome or produce a wrong output, e.g.

['f', 'i', 'r', 's', 't', '\n', 's', 'e', 'c', 'o', 'n', 'd', '\n', 't', 'h', 'i', 'r', 'd', '\n']

or

first
second
third

What is the most pythonic function to get this done? My starting point so far has been

with open('list_of_words', 'r') as list_of_words:
    # Do something...
print(list_of_strings)



Solution

You just can use list(..) here on the file handler. Since the strings will contain a new line, you might want to use str.rstrip to remove the '\n' part at the right:

with open('list_of_words', 'r') as f:
    list_of_strings = list(map(str.rstrip, f))
print(list_of_strings)




Comments (5)

  • +0 – Thanks, this is perfect. — Jul 21, 2019 at 19:03  
  • +0 – One question: Where does str in str.rstrip point to, i.e. how does the interpreter know that str refers to the individual strings inside list_of_strings? This works fine (while e.g. map(rstrip(), f) does not), it's just that str seems to fall out of the blue. — Jul 21, 2019 at 19:25  
  • +0 – @david: str referis to the str class. If a method it defined on the class level (and it is not a static method or class method), then str.foo(x) is the same as x.foo() given x is a string. — Jul 21, 2019 at 19:26  
  • +0 – Is there a technical name for this behaviour? — Jul 22, 2019 at 14:52  
  • +0 – @david: in mathematics, that would be "partial application". The behavior s explained here stackoverflow.com/q/2709821/67579 for example. — Jul 22, 2019 at 15:00