Retrieve list written to file with Python

3

I would like to go to my file that contains the following

['teste1', '27-12-18', '12/5/2015', 'Aberta']
['teste2', '27-12-18', '6/7/7', 'Aberta']
['teste3', '27-12-18', '12/5/6', 'Fechada']

and only show if the 3 field is Open I have the following code;

Writing to file:

def annexsentence():

    data_inicio=input("Nome da Tarefa :")

    data_final=input("Data Final :") #placeholder ano-mes-dia

    data_atual = datetime.datetime.now().strftime("%d-%m-%y")

    estado="Aberta"

    lista=[data_inicio,str(data_atual),str(data_final),estado]

    annexsentence=open("ficheiro.txt","a")

    annexsentence.write(str(lista)+"\n")

    annexsentence.close()

annexsentence()

Reading the file:

def mostrar():
    #ler linha a linha
    with open("ficheiro.txt") as arquivo:
        for linha in arquivo:
            if linha[3]=="Aberta":
                print (linha)
            else:
                print("ola")
mostrar()

Can someone explain what I should do to fix it?

If you do print(linha[3]) return and test and get linha[0] [ appears

    
asked by anonymous 27.12.2018 / 17:19

2 answers

2

As commented out, the form you used to write to the file is not ideal for retrieving the data later. You just turned the list into a string before writing to the file, but this process is not trivially reversible and can cause numerous side effects.

annexsentence.write(str(lista)+"\n")

The best way to do this is to use some format that is reversible. You can, for example, use the JSON format:

import json

annexsentence.write(json.dumps(lista) + "\n")

And while reading, retrieve the data with dados = json.loads(linha) . This way, dados will again list the values you want.

Another way is to serialize your object. One way of doing this is with the pickle where, in writing, you do :

import pickle

annexsentence.write(pickle.dumps(lista) + "\n")

While reading, to retrieve data, you can dados = pickle.loads(linha) . Again dados will be a list with the desired values.

Study the solutions and see which one best fits your needs.

    
27.12.2018 / 17:45
0

TL; DL
Use re.sub() , and split() , see the example below:

import re

ln = "['teste1', '27-12-18', '12/5/2015', 'Aberta']"

# Removendo os caracteres indesejados
ln = re.sub("\[|\]|'","",ln)

# Convertendo a string em uma lista
lst = ln.split(', ')

print(lst[3])
Aberta

See working at Repl.it

  

Adapting to your file reading function:

def mostrar():
    #ler linha a linha
    with open("ficheiro.txt") as arquivo:
        for linha in arquivo:
            ln = linha.strip()
            ln = re.sub("\[|\]|'","",ln)
            lst = ln.split(', ')
            if lst[3]=="Aberta":
                print (linha)
            else:
                print("ola")
mostrar()
['teste1', '27-12-18', '12/5/2015', 'Aberta']

['teste2', '27-12-18', '6/7/7', 'Aberta']

ola

Obs.
If you can change the way to generate the file, I suggest storing each line with values just separated by commas, like this:

teste1,27-12-18,12/5/2015,Aberta
teste2,27-12-18,6/7/7,Aberta
teste3,27-12-18,12/5/6,Fechada

This way you would not need to use re and your reading function should be changed to a simpler form:

def mostrar():
    #ler linha a linha
    with open("ficheiro.txt") as arquivo:
        for linha in arquivo:
            ln = linha.strip()
            lst = ln.split(',')
            if lst[3]=="Aberta":
                print (linha)
            else:
                print("ola")
    
27.12.2018 / 18:37