简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM