gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:03:22 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com