简体   繁体   中英

How to sort file contents into 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

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

I'll provide some pseudocode to help you out.

First your data structure should look like this:

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

Then the logic you should follow should be something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM