如何将列表附加到文件

时间:2018-06-06 00:28:40

标签: python list sorting

如何将输出写入一个文件,以后可以在第二个元素排序的列表中读取。

scores.txt中的输入为:

test 1: 1
test 2: 5
test 3: 2
test 4: 6

程序:

def sorter():
    scores = "scores.txt"
    highScores = list()   # place all your processed lines in here

    with open(scores) as fin:
        for line in fin:
           lineParts = line.split(": ")
           if len(lineParts) > 1:
               lineParts[-1] = lineParts[-1].replace("\n", "")
               highScores.append(lineParts)   # sorting uses lists
        highScores.sort(key = lambda x: x[1])
    print(highScores)

输出是:

[['test 1', '1'], ['Test 3', '2'], ['Test 2', '5'], ['Test 4', '6']]

1 个答案:

答案 0 :(得分:1)

我认为您希望dump要提交的列表。

import pickle

with open('filename','wb') as file:
    pickle.dump(list,file)

如果您只想阅读

with open ('filename', 'rb') as file:
    list = pickle.load(file)

仅对列表进行排序:

from operator import itemgetter

sorted(list, key=itemgetter(1)) //1 because is the second element you want