【发布时间】:2020-05-01 00:18:32
【问题描述】:
我的目标是获取一个包含班级学生姓名和分数的现有文件,并逐一替换每个学生的分数。首先,我以读取模式打开文件并为学生创建字典,然后向用户询问新分数并替换字典中的值。然后我想做的是用新分数替换文件中的行,但是我只能设法将它们添加到现有分数中。
这是我的代码:
def editStudent(classfile):
with open(f'Class {classfile}.txt','r+') as file:
studentNo = int(file.readline())
data = file.readlines()
for i in range(0,studentNo):
piece = data[i]
contents = piece.split(',')
name = contents[0]
score = contents[1]
readin = {}
readin[name] = int(score)
replacement = int(input('Please enter a new score for ' + name + ' > '))
readin[name] = int(replacement)
for key,value in readin.items():
studentdata = '{},{}\n'.format(key, value)
file.close()
with open(f'Class {classfile}.txt','w') as file:
file.write(str(studentNo) + '\n')
file.write(studentdata)
这是文本文件的样子:
2
Max Sinclair,100
Random Guy,50
文件的第一行指定班级中的学生人数,我用这个变量在我的函数内部创建一个循环来告诉程序需要替换多少学生。
这是我运行程序并为每个学生输入新分数时的输出:
2
Max Sinclair,100
Random Guy,50
Max Sinclair,99
Random Guy,49
【问题讨论】:
-
open(f'Class {classfile}.txt','w')
标签: python function loops file