2

需要创建数据库,我正在努力从 txt 文件中删除。

我不知道如何让它从读取变量中删除 nameToFind。有人建议我使用字典?这是我到目前为止所拥有的:

def displayMenu():
    print ("1 - Add item")
    print ("2 - Delete item")
    print ("3 - Find item using name")
    print ("4 - Find item using score")
    print ("5 - Update score")
    print ("9 - Quit")


def getMenuChoice():
    try:
        choice = int(input("Please enter your choice:"))
    except Exception:
        return 0
    else:
        return choice


def addItem(newName, newScore, datafile):
    myFile = open(datafile, "a")
    myFile.write(newName + ":" + newScore + "\n")
    myFile.close()

def deleteItem(nameToFind, datafile):
    deletedword = str(nameToFind)
    myFile = open("datafile.txt", "r")
    read = myFile.read()
    for line in read:
        lines = line.split(":")
        #if lines == deletedword:
            #deleted = read.remove(deletedword)
            #print(deleted)
    myFile.close()
    deleted = read.remove[nameToFind]
    print(deleted)
    myFile1 = open("datafile.txt", 'w')
    myFile1.write(deleted)
    myFile1.close()    


def findItemUsingName(nameToFind, datafile):
    scores = {}
    myFile = open("datafile.txt", 'r')
    for line in myFile:
        lineValues = line.split(":")
        scores[lineValues[0]] = lineValues[1]
    myFile.close()          




highestScores = {}

choice = 0
while choice in [1, 2, 3, 4, 5, 0]:

    displayMenu()
    choice = getMenuChoice()

    if choice == 0:
        print ("Please enter 1, 2, 3, 4, 5 or 9")


    elif choice == 1:
        newName = input("Please enter the new name:")
        try:
            newScore = int(input("Please enter score for " + newName + ":"))
        except Exception:
            print("You must enter an integer for score")
        else:
            addItem(newName, str(newScore), "datafile.txt")


    elif choice == 2:
        print("Delete item")
        nameToFind = input("What is the name to delete? ")
        deleteItem(nameToFind, "datafile.txt")
    elif choice == 3:
        print("Find item using name")
        nameToFind = input("What is the name to find? ")
        findItemUsingName(nameToFind, "datafile.txt")
    elif choice == 4:
        print("Find item using score")
    elif choice == 5:
        print("Update score")

您还需要一个名为“datafile”的 .txt 文件。

4

2 回答 2

0

过程

  • 将数据读入内存,
  • 过滤掉不需要的数据,
  • 用内存中的数据写出文件。

不是工业实力数据库,但你明白了。例如,您可以决定写入临时文件并在成功时重命名。

代码

def read_database(datafile):
    with open(datafile, "r") as myFile:
        return dict(line.rstrip().split(':') for line in myFile)

def write_database(datafile, data):
    with open(datafile, "w") as myFile:
        myFile.write("".join("%s:%s\n" % (k, v) for k, v in data.iteritems()))

def deleteItem(nameToFind, datafile):
    data = read_database(datafile)
    data.pop(nameToFind, None)
    write_database(datafile, data)

if __name__ == '__main__':
    datafile = "datafile.txt"
    data = {
        "Smith": 89,
        "Jones": 58,
        "Kozicki": 100,
    }
    write_database(datafile, data)
    deleteItem("Jones", datafile)

原语

使用这些原语,您可以稍微重写您的代码:

def addItem(newName, newScore, datafile):
    data = read_database(datafile)
    data[newName] = newScore
    write_database(datafile, data)

def findItemUsingName(nameToFind, datafile):
    data = read_database(datafile)
    return data.get(nameToFind)
于 2013-03-20T18:05:27.510 回答
0

我会打开datafile一个临时文件,读入内容datafile并检查您删除的单词,如果该行很好,请将其写入临时文件。读完整个文件后,将其删除并复制temp以替换它。

中的功能shutil对文件删除/移动有好处(并os具有unlink删除文件的功能)。

import os, shutil

# read one file whilst writing to an intermediate file
with open("datafile.txt", "r") as io, open('temp', 'w') as oo:
    for line in io.readlines():
        if deletedWord not in line.split(':'):
            oo.write('%s' % line)

# delete the original file
os.unlink("datafile.txt")  

# move your new file sans deleted word over to datafile
shutil.move('temp', "datafile.txt")  
于 2013-03-20T17:49:27.343 回答