如何使用python删除文本文件的一行

时间:2016-02-14 11:46:57

标签: python file python-3.x text

Python 3.5.1 我正在创建一个对文本文件进行排序的程序。该程序应该重写文本文件,以便只保留每个学生的三个最新分数。我目前在Aum Patel'在文本文件中;我希望python在读取之前删除最旧版本的乐谱。文本文件如下 - > '名称''得分'

这是文本文件(称为' Quiz-1'):

Aum Patel,10
Guy,9
Aum Patel,8
Amanjeet Singh,2
Aum Patel,4
Aum Patel,10
Chong Singh,1
Amanjeet Singh,7

这是Python 3代码:

import csv
import operator

n=0
quizGrades = open('Quiz-1.txt' , 'r')

grades = csv.reader(quizGrades, delimiter =',')
sortedGrades = sorted(grades, reverse= False, key=operator.itemgetter(0))
person=[]
SCORE=[]
for eachline in sortedGrades:
    person.append(eachline[0])
    SCORE.append(eachline[1])
    print(person[n],': scored ',SCORE[n])
    print()
    n=n+1
    quizGrades.close()

1 个答案:

答案 0 :(得分:1)

为了跟踪各种学生,我建议使用字典来存储所有内容。然后,每个条目都包含所有分数的列表。

首先阅读测验文件,然后建立字典。然后迭代遍历所有条目,从每个条目写出最后3个,如下所示:

import csv

d_students = {}

with open('input.txt', newline='') as f_input, open('output.txt', 'w', newline='') as f_output:
    csv_input = csv.reader(f_input)
    csv_output = csv.writer(f_output)

    for student, score in csv_input:
        if student in d_students:
            d_students[student].append(int(score))
        else:
            d_students[student] = [int(score)]

    for student, scores in d_students.items():
        scores = scores[-3:]    # Take the last 3 scores in each list
        print("Student {} has an average score of {:.1f}".format(student, sum(scores) / float(len(scores))))

        for score in scores:
            csv_output.writerow([student, score])

对于您拥有d_students的数据,我们会保留以下内容:

{'Guy': ['9'], 'Amanjeet Singh': ['2', '7'], 'Chong Singh': ['1'], 'Aum Patel': ['10', '8', '4', '10']}

平均值是通过将得分相加并除以每个列表中的得分总数来计算的,这将显示以下输出:

Student Amanjeet Singh has an average score of 4.5
Student Chong Singh has an average score of 1.0
Student Aum Patel has an average score of 7.3
Student Guy has an average score of 9.0

从这里开始,脚本会输出每个列表中的最后3个条目,为您提供以下输出文件:

Chong Singh,1
Guy,9
Amanjeet Singh,2
Amanjeet Singh,7
Aum Patel,8
Aum Patel,4
Aum Patel,10

注意,如果您在Python 3中使用csv,则需要使用newline=''参数打开该文件。