How to change an attribute in a list of objects and write this list in a file

0

I have a list of conList objects that I want to change an attribute of an object and then write that list to a file, where each line of the file is an attribute of each object in the list. How do I do this?

Edit:

Code that I have so far:

 def carregarConsumiveis(self):
    consList=[]
    arq=open('Consumiveis.dat', 'r')
    i=0
    tipo=''
    nome=''
    codigo=''
    quantidade=''
    preco=''
    for linha in arq:
        if i==0:
            tipo=linha
        elif i==1:
            nome=linha
        elif i==2:
            codigo=linha
        elif i==3:
            quantidade=linha
        elif i==4:
            preco=linha
            consumivelarq=Consumivel(tipo,nome,codigo,quantidade,preco)
            consList.append(consumivelarq)
            i = -1
        i+=1
    arq.close()
    return consList

I want to change an attribute of an object with a certain name, and rewrite it in the file.

    
asked by anonymous 12.01.2018 / 03:47

1 answer

0

I solved the problem, thanks to everyone who helped. Here is the solution I found for this problem.

def adicionarQuantidade(self,consumivel):

    consList = self.carregarConsumiveis()
    for con in consList:
        if con.nome == (consumivel.nome+'\n'):
            newqntd=(int(con.quantidade))+(int(consumivel.quantidade))
            con.quantidade=newqntd
            self.reescrevendo(consList)

def reescrevendo(self, consList):

    arq = open('Consumiveis.dat', 'w')
    for i in consList:
        arq.write(str(i.tipo))
        arq.write(str(i.nome))
        arq.write(str(i.codigo))
        arq.write(str(i.quantidade)+'\n')
        arq.write(str(i.preco))
    arq.close()

The function adicionarQuantidade is checking if any object in the file has the same name as the object that I want to save, if it has it, edit the quantity attribute, adding the old attribute to the new attribute and finally calling the reescrevendo function rewrites the list to the file.

    
14.01.2018 / 20:19