2014-09-25 91 views
-4

我的問題是我想將文件的每一行追加到列表中。 這裏是什麼樣子的文本文件:將每行從文本文件追加到列表

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

我想每一行的內容附加到它自己的列表:

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

'line.split( 「」)'? – 2014-09-25 12:42:09

+1

列表列表將比數百個單獨的變量更方便。首先,迭代它們會更容易。 – DSM 2014-09-25 12:43:22

+0

我不知道如何閱讀文本文件。到目前爲止,我只使用輸入 – Jay 2014-09-25 12:47:44

回答

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

+0

我猜OP希望列表元素爲'int',爲什麼要製作字典? – 2014-09-25 13:21:22