Yasin Khan
Yasin Khan

Reputation: 21

How to append list to a file

How do you write the output into a file which can be read as a list later on sorted by the second element.

The inputs in scores.txt are:

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

program:

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)

the outputs are:

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

Upvotes: 0

Views: 55

Answers (1)

João Castilho
João Castilho

Reputation: 487

I think you want to dump the list to file.

import pickle

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

When you want to read it's only

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

To sort the list of lists is only:

from operator import itemgetter

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

Upvotes: 1

Related Questions