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

时间:2015-09-26 19:41:13

标签: python list file

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

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

2 个答案:

答案 0 :(得分: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)

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

答案 1 :(得分:3)

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

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

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