[python] Python, add items from txt file into a list

Say I have an empty list myNames = []

How can I open a file with names on each line and read in each name into the list?

like:

>     names.txt
>     dave
>     jeff
>     ted
>     myNames = [dave,jeff,ted]

This question is related to python file-io

The answer is


names=[line.strip() for line in open('names.txt')]

f = open('file.txt','r')

for line in f:
    myNames.append(line.strip()) # We don't want newlines in our list, do we?

Read the documentation:

with open('names.txt', 'r') as f:
    myNames = f.readlines()

The others already provided answers how to get rid of the newline character.

Update:

Fred Larson provides a nice solution in his comment:

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

#function call
read_names(names.txt)
#function def
def read_names(filename): 
with open(filename, 'r') as fileopen:
    name_list = [line.strip() for line in fileopen]
    print (name_list)

This should be a good case for map and lambda

with open ('names.txt','r') as f :
   Names = map (lambda x : x.strip(),f_in.readlines())

I stand corrected (or at least improved). List comprehensions is even more elegant

with open ('names.txt','r') as f :
    Names = [name.rstrip() for name in f]

Names = []
for line in open('names.txt','r').readlines():
    Names.append(line.strip())

strip() cut spaces in before and after string...


The pythonic way to read a file and put every lines in a list:

from __future__ import with_statement #for python 2.5
Names = []
with open('C:/path/txtfile.txt', 'r') as f:
    lines = f.readlines()
    Names.append(lines.strip())