Search code examples
pythonfilelines

How to eliminate blank lines from a file


I'm working on a project where I have to manage a list of clients, which is stored on a txt file. My problem is the following, when I work with the list I upload it into memory into a list=[] variable, and then I work with it, is actually a list of objects, my problem comes when I try to delete a certain line from the list, I delete it form the list=[] and after that I rewrite the txt file with the new list but the problem is that i'm left with blank lines and when I try to execute again the program the list can not be read. I also like to mention that I made a function to eliminate the blank lines but it doesn't seem to work, any help?

This is the function to eliminate the blank lines

def elimina_client(self):
    f = open("clienti.txt","r")
    lines=f.readlines()
    f.close
    f = open("clienti.txt","w")   
    for line in lines:
        if line!="":
             f.write(line)

This is the function for rewriting the file

def rescrie_clienti(self):
    """This function rewrites the clienti document"""
    with open(self.fisier2,'w') as f:
        for i in range(0,len(lista.lista_clienti)):
                if i==len(lista.lista_clienti)-1 :
                    s =str(lista.lista_clienti[i].get_identitate())+","+str(lista.lista_clienti[i].get_nume())+","+str(lista.lista_clienti[i].get_cnp()+","+str(lista.lista_clienti[i].get_filme_inchiriate())+","+str(lista.lista_clienti[i].get_inchirieri()))
                    f.write("\n")
                    f.writelines(s)
                else:
                    s =str(lista.lista_clienti[i].get_identitate())+","+str(lista.lista_clienti[i].get_nume())+","+str(lista.lista_clienti[i].get_cnp()+","+str(lista.lista_clienti[i].get_filme_inchiriate())+","+str(lista.lista_clienti[i].get_inchirieri()))
                    f.writelines(s)

And this is the actually function that deletes the item form the list in memory

def sterge_client(self,ident):
    "Deletes a client from the list"
    k=0
    for element in self.lista_clienti:
        if element.get_identitate()==ident:
            self.lista_clienti.remove(element)
            k=1
    if k==0:
        raise RepositoryException(["Nu exista acest ID!"])

This is the function that is suposed to remove the a line from file, what it actually does is rewriting the list with the new list=[] without a given element, then "eliminates" the blank spaces, but it doesn't seem to work, anyone know why ?

def sterge_client2(self,ident):
    lista.sterge_client(ident)
    self.rescrie_clienti()
    self.elimina_client() 

Solution

  • def elimina_client(self):
        with open("clienti.txt","r") as f:
            lines=f.readlines()
    
        with open("clienti.txt","w") as f:  
            [f.write(line) for line in lines if line.strip() ]
    

    Python3 with iterators:

    #!/usr/bin/env python3
    
    def elimina(fsrc, fdst):
      with open(fsrc,'r') as src, open(fdst,'w') as dst:
        [ dst.writelines(line) for line in src if line.strip() ]
    
    if __name__ == '__main__':
      elimina('text.txt','text_out.txt')