如何排序整个文件

时间:2015-01-21 16:33:42

标签: python python-3.3

f.sort

此功能似乎不起作用

1 个答案:

答案 0 :(得分:2)

您应该对数组进行排序,而不是文件。可以使用sorted函数对数组进行排序:

a = sorted([5, 2, 3, 1, 4])
print a
>>> [1, 2, 3, 4, 5]

您可以在docs中找到更多相关信息。

为了按照您请求的方式对数据进行排序(将名称和分数保持在一起),最好创建一个名称和分数的临时元组,然后对其进行排序。您需要提供自定义排序键以选择平均值:

data = [
    (name, score_1, score_2, score_average),
    ....
]
data.sort(key=lambda datum: datum[3])

with open("classa.txt", "w") as f:
    for entry in data:
        f.writelines(entry)

如果您需要使用它来处理现有文件,那么您需要以块为单位读取数据:

with open("classa.txt", "r") as f:
    lines = f.readlines()

data = []
while lines:
    name, score_1, score_2, avg, *lines = lines
    data.append((name, score_1, score_2, avg))

此代码需要python 3。