CRUD in Python - Search() function?

Asked

Viewed 233 times

-1

Hello, I am doing a CRUD in Python using files and while doing the function "search" I found myself in a problem.

The code is as follows::

def buscar():
n = input('Digite o nome do contato a ser pesquisado: ')
s = input('Digite o sobrenome do contato a ser pesquisado: ')
agenda = open('%s_%s.txt'%(n,s),'r')

for x in agenda.readlines():
    print(x)
agenda.close()

Thus, the code returns me what I ask: the contact data in the file. But I get an error when requesting a contact that does not exist.

I wonder how I can fix the code to display an error message to the user when not found the contact that was requested.

Entire code:

import os
#Funções
def cadastrar():
    n = input('Digite seu nome: ')
    s = input('Digite seu sobrenome: ')
    t = int(input('Digite seu telefone: '))
    e = input('Digite seu email: ')
    agenda = open('%s_%s.txt' %(n,s),'a')
    agenda.write('%s %s, %d, %s\n'%(n, s, t, e))
    agenda.close()
def buscar():
    n = input('Digite o nome do contato a ser pesquisado: ')
    s = input('Digite o sobrenome do contato a ser pesquisado: ')
    agenda = open('%s_%s.txt'%(n,s),'r')

    for x in agenda.readlines():
        print(x)
    agenda.close()
def deletar():
    n = input('Digite o nome que deseja apagar: ')
    s = input('Digite o sobrenome que deseja apagar: ')
    os.remove('%s_%s.txt'%(n,s))

#Função principal

def main():
    print('              MENU')
    print('1. Novo contato\n2. Buscar contato pelo nome')
    print('3. Atualizar contato\n4. Apagar contato\n0. Sair')
    op = 1
    while op!=0:
        op = int(input('\nDigite a opção: '))
        if op==1:            
            cadastrar()            
        elif op==2:
            buscar()
        elif op==4:
            deletar()            
        elif op==0:
            print('Programa finalizado.')
            break
        else:
            print('Opção incorreta, tente novamente. ')
main()

1 answer

0


Milena, the open function is generating exception by not finding the file.

The idea is you check the existence of the same before trying to open:

def buscar():
    n = input('Digite o nome do contato a ser pesquisado: ')
    s = input('Digite o sobrenome do contato a ser pesquisado: ')

    if os.path.isfile('%s_%s.txt'%(n,s)):
      agenda = open('%s_%s.txt'%(n,s),'r')

      for x in agenda.readlines():
          print(x)
      agenda.close()
    else:
      print('Contato não encontrado.')

You can also treat by exception:

def buscar():
    n = input('Digite o nome do contato a ser pesquisado: ')
    s = input('Digite o sobrenome do contato a ser pesquisado: ')

    try:
      agenda = open('%s_%s.txt'%(n,s),'r')

      for x in agenda.readlines():
          print(x)

      agenda.close()
    except:
      print('Contato não encontrado.')

Browser other questions tagged

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