繁体   English   中英

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

[英]How to sort file contents into list

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

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

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

Super:1
Super:4
Super:6

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

我的代码如下:

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

您可以使用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)

只需将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))

我会提供一些伪代码来帮助你。

首先,您的数据结构应如下所示:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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