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

Asked

Viewed 432 times

0

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

Edit:

Code 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 in the file.

  • 2

    Is there any way to ask the question what code you have today? If each line in the file will be an attribute and you have a list of objects, how will you know when you finish one and start another in the file?

  • is also an example of the final file format, and mainly the code you have tried to make.

1 answer

0

I solved the problem, thank you to all who helped. Here’s the solution I found to 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 I want to save, if it edits the quantity attribute, adding the old one with the new one and finally calls the function reescrevendo rewriting the list in the archive.

  • Thank you for sharing your solution. Don’t forget to mark your answer as a solution to your question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.