说我有一个空列表myNames = []
如何在每行上打开一个带有名称的文件,并将每个名称读入列表?
像:
> names.txt
> dave
> jeff
> ted
> myNames = [dave,jeff,ted]
答案 0 :(得分:36)
with open('names.txt', 'r') as f:
myNames = f.readlines()
其他人已经提供了如何摆脱换行符的答案。
<强>更新强>:
Fred Larson在他的评论中提供了一个很好的解决方案:
with open('names.txt', 'r') as f:
myNames = [line.strip() for line in f]
答案 1 :(得分:8)
f = open('file.txt','r')
for line in f:
myNames.append(line.strip()) # We don't want newlines in our list, do we?
答案 2 :(得分:4)
names=[line.strip() for line in open('names.txt')]
答案 3 :(得分:1)
#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)
答案 4 :(得分:1)
这应该是map和lambda的好例子
with open ('names.txt','r') as f :
Names = map (lambda x : x.strip(),f_in.readlines())
我的立场得到了纠正(或至少得到了改善)。列表理解更加优雅
with open ('names.txt','r') as f :
Names = [name.rstrip() for name in f]
答案 5 :(得分:0)
Names = []
for line in open('names.txt','r').readlines():
Names.append(line.strip())
strip()在字符串之前和之后剪切空格......
答案 6 :(得分:0)
读取文件并将每行放入列表的pythonic方法:
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())