Error reading binary python file

Asked

Viewed 115 times

1

good night.

I am trying to read the contents of a binary file in Python to assemble a dictionary, but when reaching the end of the file the program is "flying" and I am not able to capture the exception. When I debug, I see that it includes the data in the dictionary correctly, but when it reaches the last position of the file, the command pickle.load(file) "flies" and no other line of code after while is executed. Nor does the file.close() command run.

Opening the file . dat in a notepad, its display is similar to the following excerpt:

S'001'
p0
.S'Toninho Silva'
p0
.S'Prefeito'
p0
.S'Tijuca'
p0
.S'2300'
p0
.

The code that reads from the binary file, writes to the dictionary and, at the end, displays on the screen the result (which is part of the contents of the dictionary) follows below:

try:
    dic_votos_candidato = dict()
    arquivo = open('eleicoes.dat', 'rb')
    while arquivo:
        soma = 0
        cod_candidato = pickle.load(arquivo)
        nome_candidato = pickle.load(arquivo)
        cargo = pickle.load(arquivo)
        regiao = pickle.load(arquivo)
        num_votos = pickle.load(arquivo)
        if dic_votos_candidato.get(nome_candidato):
            soma = int(dic_votos_candidato[nome_candidato])
            soma = soma + int(num_votos)
            dic_votos_candidato[nome_candidato] = soma
        else:
            dic_votos_candidato[nome_candidato] = int(num_votos)
    arquivo.close()
    for chave in dic_votos_candidato.keys():
        print chave, dic_votos_candidato[chave]
except IOError:
    print "Erro ao abrir o arquivo. Verifique se o arquivo foi criado."
    print "Caso o arquivo ainda nao exista, use a opcao 1 do menu principal para cria-lo."
    exit()
finally:
    opcao = raw_input('\nPara continuar, digite a opcao desejada: ')
    trata_listar(opcao)

Thanks for your help!

No answers

Browser other questions tagged

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