Recover List Written in Python File

Asked

Viewed 379 times

4

I’d 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;

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()

File reading:

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 to me what I should do to fix?

If you do print(linha[3]) back and test and stick linha[0] appears [

  • You who generated the file?

  • yes, I have more code but I think the problem is here

  • The question is how Python will interpret the contents of the file. The way you wrote the file is not such a trivial way to recover the structure, so probably the ideal solution is to redo the writing logic of the file. You can use JSON or serialize the object, for example.

  • but in this case I really have to use python is for a course project, but what is confusing me and just appear 1 character and not everything

  • The suggestion is to still continue using Python, but writing the file in a way that is simpler to recover the data. Please edit the question and add the code you use to write to the file.

2 answers

6


As commented, the way you used to write to the file is not the ideal one to recover the data later. You just converted the list into a string before writing to the file, but this process is not trivially reversible and can generate numerous side effects.

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

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

import json

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

And while reading, recover data with dados = json.loads(linha). In this way, dados will again be a list of values you want.

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

import pickle

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

While in reading, to recover the data, you can do dados = pickle.loads(linha). Again dados will be a list of desired values.

Study the solutions and see which is best suited to your needs.

-1

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 on Repl.it

Adapting to your file read 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 Voce can change the way you generate the file, I suggest that you store 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

That way you wouldn’t have to use re and its 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")

Browser other questions tagged

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