繁体   English   中英

如何从 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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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