尝试从“ txt”文件中删除字符串时出错-联系人列表程序

时间:2019-06-09 11:20:34

标签: python

我正在创建一个联系人列表/预订程序,可以为您创建新的联系人。将它们保存在'txt'文件中。列出所有联系人,并删除现有联系人。好吧。在我的删除功能中,发生了一个错误,我不太清楚为什么。运行时外壳上没有提示错误。旨在询问用户要删除的联系人,在'txt'文件中找到用户所说的内容。然后删除它。它可以轻松找到它,但是根本不会删除该字符串。

我尝试了其他方法,包括if / else语句,其他在线代码(已复制)-无效。

import os, time, random, sys, pyautogui


#function for creating a new contact.
def new_contact():


    name = str(input("Clients name?\n:"))

    name = name + " -"

    info = str(input("Info about the client?\n:"))

    #starts formatting clients name and info for injection into file.

    total = "\n\n"
    total = total + name
    total = total + " "
    total = total + info
    total = total + "\n"
    #Injects info into file.


    with open("DATA.txt", "a") as file:

        file.write(str(total))
        file.close

    main()

#function for listing ALL contacts made.
def list():


    file = open("DATA.txt", "r")
    read = file.read()
    file.close


    #detects whether there are any contacts at all. If there are none the only str in the file is "Clients:"
    if read == "Clients:":
        op = str(input("You havn't made any contacts yet..\nDo you wish to make one?\n:"))


        if op == "y":
            new_contact()


        else:
            main()

    else:
        print (read)
        os.system('pause')
        main()


#Function for deleting contact
def delete_contact():


    file = open("DATA.txt", "r")
    read = file.read()
    file.close


    #detects whether there are any contacts at all. If there are none the only str in the file is "Clients:"
    if read == "Clients:":
        op = str(input("You havn't made any contacts yet..\nDo you wish to make one?\n:"))


        if op == "y":
            new_contact()


        else:
            main()


    else:
        #tries to delete whatever was inputted by the user.
        file = open("DATA.txt", "r")
        read = file.read()
        file.close


        print (read, "\n")


        op = input("copy the Clinets name and information you wish to delete\n:")

        with open("DATA.txt") as f:
            reptext=f.read().replace((op), '')


        with open("FileName", "w") as f:
            f.write(reptext)
            main()


#Main Menu Basically.
def main():


    list_contacts = str(input("List contacts? - L\n\n\nDo you want to make a new contact - N\n\n\nDo you want to delete a contact? - D\n:"))


    if list_contacts in ("L", "l"):
        list()


    elif list_contacts in ("N", "n"):
        new_contact()


    elif list_contacts in ("D", "d"):
        delete_contact()


    else:
        main()



main()

希望删除用户从txt文件输入的所有内容。没有错误显示在外壳/控制台上,好像程序认为它已经完成了,但是没有。 txt文件中的内容包含:

客户:

Erich-开发人员

鲍勃-测试对象

2 个答案:

答案 0 :(得分:0)

在删除功能中,您无需打开DATA.txt,而是打开“ FileName”

答案 1 :(得分:0)

使用“ with”时,不需要关闭文件句柄。另外,file.close()是一个函数,您没有调用该函数,只是调用了它的地址。 另外,在删除功能中,您打开的是“ fileName”而不是“ DATA.txt”