从文件中删除,Python

时间:2013-03-20 17:45:22

标签: python

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

我不知道如何从read变量中删除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文件。

2 个答案:

答案 0 :(得分: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")  

答案 1 :(得分: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)