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

标签 python list file

我需要一个解决方案来像下面这样对我的文件进行排序:

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

目前我的文件如下所示:

Super:1
Super:4
Super:6

我需要帮助来跟踪每个类(class)成员在测验中获得的分数。有 学校三个类(class),每个类(class)的数据需要分开保存。

我的代码如下:

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

最佳答案

您可以使用字典对数据进行分组,特别是 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))

关于python - 如何将文件内容排序到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32801242/

相关文章:

python - 如何使用(样本、X、Y)的 2D 特征和形状标准化数据?

当键出现多次时要字典的Python列表列表

python - python计算不同数据帧中两个列表之间的匹配

python - 似乎无法在此列表中最后添加百分比?

file - Matlab 的 "fileattrib"函数中可能存在错误。解决方法?

java - 如何获取 .java 文件的目录

python - 如何将 mmap 中的行读入字典?

python - PySide QTableView setData 多个单元格

python - 包含1的随机数函数python?

javascript - 如何在 Javascript 前端使用 Firebase Firestore .push() 方法