如何从 Python 中的文件中删除特定行

How to delete a particular line from file in Python

def deleteEmployee(self,code,name):
  with open("employee.data","r+") as file:
  # data=file.readlines()
    for num, i in enumerate(file,1): 
       print(i)
       a=i[:len(i)-1]
       if str(a)==str(code):
          print("found at",num)
          file.seek(num)
          file.write("\n")
    file.close()

我只想写一个文件处理代码。在这里,我定义了删除函数,如果文件中存在特定代码但它不起作用,我想删除该函数。

这段代码应该能达到你想要的效果:

def deleteEmployee(self,code,name):
    with open("employee.data","r+") as file:
        new_content = ""
        for num, line in enumerate(file,1): 
            print(line)
            a=line[:-1]
            if str(a)==str(code):
                print("found at ",num)
                new_content += "\n" #Adds newline instead of 'bad' lines
            else:
                new_content += line #Adds line for 'good' lines
        file.seek(0) #Returns to start of file
        file.write(new_content) #Writes cleaned content
        file.truncate() #Deletes 'old' content from rest of file
        file.close()