Search code examples
pythonpython-3.xfile-manipulation

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()

I just want to write a file handling code. Here I define delete function where I want to delete particular code if exists inside the file but it's not working.


Solution

  • This code should achieve what you want:

    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()