简体   繁体   English

在Python中从txt文件中删除数据

[英]Removing data from txt file in Python

I have a txt file open in python which data has been written to. 我在python中打开了一个已写入数据的txt文件。 I need a way for only 3 parts of data to be inputted into this file before the oldest bit of data is deleted and replaced with the newer data. 我需要一种方法,在删除最旧的数据并将其替换为较新的数据之前,仅将3部分数据输入此文件。

For example: A teacher has asked me to build a system in python that askes students 10 random maths questions, before talking this quiz the student must enter their name and class number. 例如:一位老师要求我用python构建一个系统,向学生提出10个随机数学问题,在说出此测验之前,学生必须输入他们的姓名和班级编号。

When the quiz has been completed their name and score must be written to a certain file, class1.txt if they belong to class 1, class2.txt if they belong to class2 and so on. 测验完成后,必须将其名称和分数写入某个文件,如果它们属于第1类,则将它们写入class1.txt,如果属于class2,则将其写入class2.txt,依此类推。

This system is working correctly but the teacher has now asked me if it's possible for only the 3 most recent quiz results to be stored in the corresponding file. 该系统正常运行,但是老师现在问我是否可以仅将3个最新测验结果存储在相应的文件中。

Thanks a lot A GCSE student who's bricking himself 非常感谢GCSE的一名学生

You could use collections.deque like this: 您可以这样使用collections.deque

from collections import deque

with open("file.txt", "r+") as f:
    d = deque(f, 3)
    d.append(new_score)  # or use appendleft()
    f.seek(0)
    f.truncate()
    f.writelines(d)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM