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

时间:2018-06-09 09:06:04

标签: python python-3.x

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

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

1 个答案:

答案 0 :(得分:0)

此代码应达到您的目的:

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