Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort file contents into list

Tags:

python

file

list

I need a solution to sort my file like the following:

Super:1,4,6
Superboy:2,4,9

My file at the moment looks like this:

Super:1
Super:4
Super:6

I need help to keep track of the scores for each member of the class obtains in the quiz. There are three classes in the school and the data needs to be kept separately for each class.

My code is below:

className = className +(".txt")#This adds .txt to the end of the file so the user is able to create a file under the name of their chosen name.

file = open(className , 'a')   #opens the file in 'append' mode so you don't delete all the information
name = (name)
file.write(str(name + " : " )) #writes the information to the file
file.write(str(score))
file.write('\n')
file.close()    #safely closes the file to save the information
like image 957
super123 Avatar asked Jan 07 '23 11:01

super123


1 Answers

You can use a dict to group the data, in particular a collections.OrderedDict to keep the order the names are seen in the original file:

from collections import OrderedDict

with open("class.txt") as f:
    od = OrderedDict()
    for line in f:
        # n = name, s = score
        n,s = line.rstrip().split(":")
        # if n in dict append score to list 
        # or create key/value pairing and append
        od.setdefault(n, []).append(s)

It is just a matter of writing the dict keys and values to a file to get the output you want using the csv module to give you nice comma separated output.

from collections import OrderedDict
import csv
with open("class.txt") as f, open("whatever.txt","w") as out:
    od = OrderedDict()
    for line in f:
        n,s = line.rstrip().split(":")
        od.setdefault(n, []).append(s)
    wr = csv.writer(out)
    wr.writerows([k]+v for k,v in od.items())

If you want to update the original files, you can write to a tempfile.NamedTemporaryFile and replace the original with the updated using shutil.move:

from collections import OrderedDict
import csv
from tempfile import NamedTemporaryFile
from shutil import move

with open("class.txt") as f, NamedTemporaryFile("w",dir=".",delete=False) as out:
    od = OrderedDict()
    for line in f:
        n, s = line.rstrip().split(":")
        od.setdefault(n, []).append(s)
    wr = csv.writer(out)
    wr.writerows([k]+v for k,v in od.items())
# replace original file
move(out.name,"class.txt")

If you have more than one class just use a loop:

classes = ["foocls","barcls","foobarcls"]

for cls in classes:
    with open("{}.txt".format(cls)) as f, NamedTemporaryFile("w",dir=".",delete=False) as out:
        od = OrderedDict()
        for line in f:
            n, s = line.rstrip().split(":")
            od.setdefault(n, []).append(s)
        wr = csv.writer(out)
        wr.writerows([k]+v for k,v in od.items())
    move(out.name,"{}.txt".format(cls))
like image 78
Padraic Cunningham Avatar answered Jan 10 '23 22:01

Padraic Cunningham