将每行从文本文件追加到列表中

时间:2014-09-25 12:37:54

标签: python file-io

我的问题是我想将文件的每一行附加到列表中。 这是文本文件的样子:

-1,2,1
0,4,4,1

我想将每行的内容附加到它自己的列表中:

list1 = [-1, 2, 1]
list2 = [0, 4, 4, 1]

2 个答案:

答案 0 :(得分:0)

list_dict = {} # create dict to store all the lists

with open(infile) as f: # use with to open your file as it closes them automatically
   for ind,line in enumerate(f,1): # use enumerate to keep track of each line index 
       list_dict["list{}".format(ind)] = map(int,line.rstrip().split(","))# strip new line char and add each list to the dict, ind will increment line by line
print(list_dict)
{'list1': [-1, 2, 1], 'list2': [0, 4, 4, 1]}

您应该查看reading and writing files

的文档

答案 1 :(得分:-1)

我认为您需要在 Stackoverflow 中询问之前进行更多搜索,但您可以尝试一下。

file = open("text.txt")
#Now I get all lines from file via readlines(return list)
#After i use map and lambda to go each line and split by ',' and return new result
result_list_per_line = map(lambda line: line.split(','), file.readlines())

print result_list_per_lines #Ex: [[1, 2, 3, 4], [10, 20, 30, 40]]