How to sort the contents of a file in a list

I need a solution to sort my file as follows:

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

My file currently looks like this:

Super:1
Super:4
Super:6

I need help to track the grades for each member of the class obtained in the quiz. There are three classes in a school, and data must be stored 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
+4
source share
2 answers

You can use dict to group data, in particular collections.OrderedDict , to keep order when names are displayed in the source 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)

dict , csv, -.

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())

, tempfile.NamedTemporaryFile , 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")

, :

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))
+6

, .

:

data = {'name': [score1, score2, score3]}

, , :

Read the file line-by-line
    if name is already in dict:
       append score to list. example: data[name].append(score)
    if name is not in dict:
       create new dict entry. example: data[name] = [score]

Iterate over dictionary and write each line to file
+3

Source: https://habr.com/ru/post/1609126/


All Articles