How do I store data and not delete when the program ends?

Asked

Viewed 72 times

0

How do I make sure that when a data is stored, it is not deleted from the program ending? for example:

LISTA = ['Morango', 'Abacate']
ADD_ITEM = input('Digite algo que deseja adcionar:')
LISTA.append(ADD_ITEM)

While the program is running, the value is stored in LISTA. However, at the end of the program, the stored value simply disappears. How am I supposed to fix this?

I’ve tried the open, but as I don’t know how to use it very well, I ended up failing.

I’ve used every kind of list.

2 answers

1


You need to save this list to a file, and read this file when you run the program (if it exists).

The hardest part of doing this is translating your data into a file and vice versa. I’ll show you 3 methods here, in a more or less didactic progression, I hope it helps.

METHOD 1

In your case, which is just a list of strings, we can organize in a simple way by saving a file with each element in a row. You would then have:

LISTA = ['Morango', 'Abacate']

That turns the file "LIST.txt":

Morango
Abacate

Remember that a line break is actually a special character \n, then in fact the contents of the file is:

Morango\nAbacate\n

With that in mind, let’s go to the code. It’s well commented for you to follow:

import os

LISTA = []

## Carrega a lista do arquivo
# Abre o arquivo (se ele já existe)
if os.path.exists("LISTA.txt"):
    # Abre o arquivo para leitura ('r' -> read)
    file = open("LISTA.txt", 'r')
    # Lê o arquivo linha por linha e coloca na lista
    for item in file.readlines():
        LISTA.append(item[:-1]) # Esse [:-1] tira o último caractere, um "\n"
    # Fecha o arquivo
    file.close()

## Seu código
ADD_ITEM = input('Digite algo que deseja adcionar:')
LISTA.append(ADD_ITEM)

## Salva a lista no arquivo
# Abre o arquivo para escrita ('w' -> write)
file = open("LISTA.txt", 'w')
# Itera a lista e escreve cada item no arquivo
for item in LISTA:
    # O str() converte o item em uma string
    # O '\n' no final é uma quebra de linha, pra cada item sair numa linha
    file.write(str(item) + '\n')
# Fecha o arquivo
file.close()

METHOD 1++

It is possible to use some Python features to dry this code, I commented what changed:

import os

LISTA = []

## Carrega a lista do arquivo
# Abre e fecha o arquivo (se ele já existe)
if os.path.exists("LISTA.txt"):
    with open("LISTA.txt", 'r') as file:
        # O resultado dessa função já é a lista que a gente quer
        # Deixa o "\n" e não adiciona na hora de escrever
        LISTA = file.readlines()

## Seu código
ADD_ITEM = input('Digite algo que deseja adcionar:')
LISTA.append(ADD_ITEM+"\n") # adiciona o "\n" só nos itens novos

## Salva a lista no arquivo
# Abre e fecha o arquivo
with open("LISTA.txt", 'w') as file:
    file.writelines(LISTA)

METHOD 2

Now, if you want to store more complex things than a list, this process starts to get too painful. So for this there is the module pickle, python native. This module takes variables and saves them in a "pickle", a binary file that can be opened later and recover the entire data structure, without worrying about doing this translation in hand.

I made an example using the pickle, well commented also:

import os
import pickle

LISTA = []

## Carrega a lista do arquivo
# Abre e fecha o picles (se ele já existe)
if os.path.exists("LISTA"):
    # Abre o arquivo em modo de leitura binária 'rb'
    with open("LISTA", 'rb') as file:
        LISTA = pickle.load(file)

## Seu código
ADD_ITEM = input('Digite algo que deseja adcionar:')
LISTA.append(ADD_ITEM)

## Salva a lista no picles
# Abre o arquivo em modo de escrita binária 'wb'
with open("LISTA", 'wb') as file:
    pickle.dump(LISTA, file)

## Não é possível ler o picles no editor de texto,
## então imprimo os valores aqui pra ver
print(LISTA)
  • Thanks bro, you helped a lot!

-1

It depends on the purpose of your application.

It can be Serialization in a file . txt if it is only text or in . xlsx and similar, if it is to organize the data in a spreadsheet. If you choose to use a BD, you have Sqlite which is more basic and saves records locally.

Regardless of choice, they are good options to practice and learn, if you are starting on programming.

Browser other questions tagged

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