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
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.
– jsbueno
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.
– Woss