开发者

Python, add items from txt file into a list

Say I have an empty开发者_StackOverflow社区 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]


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]


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

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


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


#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]


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())


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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜