代码再次添加行,而不是将其从文件中删除-Python

时间:2019-03-22 11:53:08

标签: python file csv

无论我对这段代码做什么,它都会始终在文件中复制该行,而不是从文件中删除它。 我曾计划挑选出要删除的部分代码。然后使用除了在“ part”变量中选择的数据以外的所有数据重写文件。

下面是我的添加功能,以显示将其添加到CSV文件的方式以及已损坏的删除功能。

def add_employee(): #THIS WORKS
    EmployeeID = int(input("Please enter the employee ID here "))
    EmployeeName = input("Please enter the name here ")
    EmployeeDep = input("Please enter the department here ")
    EmployeeDes = input("Please enter the designation here ")
    EmployeeStartDate = input("Please enter the start date here in format of DD-MM-YYYY ")
    EmployeeStatus = input("Please enter the status here : Active/Deactive ")

    with open('database.csv', "a") as f:
        employee_add = ""
        employee_add += "%s," % EmployeeID
        employee_add += "%s," % EmployeeName
        employee_add += "%s," % EmployeeDep
        employee_add += "%s," % EmployeeDes
        employee_add += "%s," % EmployeeStartDate
        employee_add += "%s," % EmployeeStatus
        employee_add += "\n"
        f.write(employee_add)
        f.close()
        print("Added correctly")
        continue_or_quit()


def remove_employee():
    id_to_delete = input("Enter the ID of the employee you would like to delete\n")

    with open('database.csv', "r+") as f:
        for line in f:
            for part in line.split():
                if id_to_delete in part:
                    print("nice")
                    for part in line.split():
                        if part != id_to_delete +"\n":
                            f.write(part)

我看过using Python for deleting a specific line in a file,但是该代码似乎不适用于我的情况。

0 个答案:

没有答案