【问题标题】:Trying to read into a file and then overwrite the file, replacing old data with new data尝试读入文件然后覆盖文件,用新数据替换旧数据
【发布时间】: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


【解决方案1】:

如果您想重新写入所有文件,您需要先用 'r' 打开它,然后用 .close() 关闭它,然后用 'w' 重新打开文件以在文件上写入。 当你在一个非空的文件上写字时,你会删除它的所有内容。

【讨论】:

  • 这种工作,但是只有列表中的最后一个学生被写入文件。
  • @sliceabled 你可以用'w'写第一个来擦除文本,然后用'a'添加其他的
猜你喜欢
  • 1970-01-01
  • 2019-03-19
  • 2013-12-14
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多