我的问题是我想将文件的每一行追加到列表中。 这里是什么样子的文本文件:将每行从文本文件追加到列表
-1,2,1
0,4,4,1
我想每一行的内容附加到它自己的列表:
list1 = [-1, 2, 1]
list2 = [0, 4, 4, 1]
我的问题是我想将文件的每一行追加到列表中。 这里是什么样子的文本文件:将每行从文本文件追加到列表
-1,2,1
0,4,4,1
我想每一行的内容附加到它自己的列表:
list1 = [-1, 2, 1]
list2 = [0, 4, 4, 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]]
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
我猜OP希望列表元素为'int',为什么要制作字典? – 2014-09-25 13:21:22
'line.split( “”)'? – 2014-09-25 12:42:09
列表列表将比数百个单独的变量更方便。首先,迭代它们会更容易。 – DSM 2014-09-25 12:43:22
我不知道如何阅读文本文件。到目前为止,我只使用输入 – Jay 2014-09-25 12:47:44