如何将文件内容排序到列表中

sup*_*123 4 python file list

我需要一个解决方案来对文件进行排序,如下所示:

Super:1,4,6
Superboy:2,4,9
Run Code Online (Sandbox Code Playgroud)

我的文件目前看起来像这样:

Super:1
Super:4
Super:6
Run Code Online (Sandbox Code Playgroud)

我需要帮助来跟踪测验中每个成员获得的分数.学校有三个班级,每个班级需要分别保存数据.

我的代码如下:

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
Run Code Online (Sandbox Code Playgroud)

Pad*_*ham 6

您可以使用dict对数据进行分组,特别是collections.OrderedDict,以保持原始文件中名称的顺序:

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)
Run Code Online (Sandbox Code Playgroud)

只需将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())
Run Code Online (Sandbox Code Playgroud)

如果要更新原始文件,可以写入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")
Run Code Online (Sandbox Code Playgroud)

如果您有多个类,只需使用循环:

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))
Run Code Online (Sandbox Code Playgroud)