add value to a list inside a file

Asked

Viewed 33 times

-1

I created a file inside that file has the lista["hello"] I tried to add a new item to the list with the following code

import subprocess
et = open("/root/projeto/a.py").read()
exec(et)
lisga.append("kkkk")
print(lisga)
r = subprocess.getstatusoutput("cat /root/projeto/a.py")[1]
print(r)

When I open the file the value remains the same hello

  • are missing some concepts of programming, files and magic for you understand there - let’s see if it appears someone who can explain to you.

  • James, by what you asked the question you would be trying to directly change the source code of a Python file just to change a list? This makes no sense in at least 99.9% of situations and I find it difficult to fit into 0.1%. Could you detail, with text, what you need to do? Maybe what you’re trying to do is not the best option - we call this the XY problem if you want to research about.

1 answer

0

I understood that you need to save the contents of a list to a file. If this is the case follow an example of a function salvar_lista that receives the parameters lista and arquivo.

To test simply call the function this way:

salvar_lista(lista, arquivo)
salvar_lista("teste", arquivo)
salvar_lista(8.99, arquivo)
salvar_lista(["R$",7.99], "outro_arquivo.txt") 

The second function ler_arquivo(arquivo) prints the contents of the specified file.

Follow the complete code. To test save in a novo_arquivo.py

lista = ["Conteúdo da lista", 9876543210, "teste"]

arquivo = "arquivo.txt"


def salvar_lista(lista, arquivo):        
        arq = open(arquivo, 'a')
        arq.writelines(str(lista) + '\n')
        arq.close()

salvar_lista(lista, arquivo)
salvar_lista("teste", arquivo)
salvar_lista(8.99, arquivo)
salvar_lista(1234567890, arquivo)
salvar_lista(["R$",7.99], "outro_arquivo.txt")


def ler_arquivo(arquivo):
        lista=[]
        arq = open(arquivo, "r")
        for linha in arq :
                print(linha)
        arq.close()


ler_arquivo(arquivo)

Output and content of arquivo.txt:

['Conteúdo da lista', 9876543210, 'teste']

teste

8.99

1234567890

Browser other questions tagged

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