使用python从文件中删除文本

2024-06-16 09:47:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为一个可以在文本文件中添加/删除/读取高分和名称的程序编写一个函数。我有addscore函数工作,但似乎无法找出删除选定的名称和文本文件的高分。这就是我如何启动delete函数的,我也有一些其他的代码,但都没有意义。事先谢谢你的帮助。你知道吗

import os
def deleteScore():
    nameDelete = input("Enter a name you would like to delete... ")
    deleteFile = open("highscores.txt", "r")
    deleteList = deleteFile.readlines()
    deleteFile.close()

这也是addscore函数,它工作正常,并以以下格式写入文本文件:

jim99

def addScore():
#asks user for a name and a score
name = input("Please enter the name you want to add... ")
score = inputInt("Please enter the highscore... ")
message = ""

#opens the highscore file and reads all lines
#the file is then closed
scoresFile = open("highscores.txt","r")
scoresList = scoresFile.readlines()
scoresFile.close()

#for each line in the list
for i in range(0, len(scoresList)):
    #checks to see if the name is in the line
    if name in scoresList[i]:
        #if it is then takes the name from the text to leave the score
        tempscore = scoresList[i].replace(name, "")

        #if the score is new then add to the list 
        if int(tempscore) < score:
            message = "Score Updated"
            scoresList[i] = (name + str(score))

            #Writes the score back into the file
            scoresFile = open("highscores.txt", "w")
            for line in scoresList:
                scoresFile.write(line + "\n")
            scoresFile.close()

            #breaks the loop
            break
        else:
            #sets the message as score too low
            message = "Score too low! Not updated"

#if the message is blank then the name wasnt found, the file is appended to the end of the file
if message == "":
    message = "New score added"
    scoresFile = open("highscores.txt", "a")
    scoresFile.write(name + str(score) + "\n")
    scoresFile.close()
print(message)

Tags: theto函数nameintxtmessageif
1条回答
网友
1楼 · 发布于 2024-06-16 09:47:14

以下是如何删除姓名和高分:

def deletescore(name, newscore):
    names = ['Alex', 'Jason', 'Will', 'Jon']
    scores = [10, 88, 55, 95]
    scores.append(newscore)
    names.remove(name)
    scores = sorted(scores, reverse=True)
   scores.remove(scores[0])
print names
print scores

deletescore('Jason',94)

结果:

['Alex', 'Will', 'Jon']
[94, 88, 55, 10]

相关问题 更多 >