How to print a particular list from a string of a .csv using python

0

The first part that is to detect the position of the list I have already achieved, the problem is at the time of the else , I would like to know a method that causes the else not to be printed together with if .

Code and the "database" below:

Code

def listar_critico():
arq = open("arquivo.csv", "r")
linhas = arq.readlines()
critico = input("Digite o nome do crítico que você deseja imprimir o registro..: ")
for linha in linhas:
    campos = linha.split(";")
    if critico in campos:
        print("\nCrítico: %s\nEmail: %s" % (campos[2], campos[3]))
    else:
        print("%s não está registrado no banco de dados." % critico)
arq.close()

Database - > link

    
asked by anonymous 08.08.2017 / 22:04

1 answer

1

The simplest solution I see for you is to use else of for (yes, that exists in Python).

The else of for is executed whenever the entire loop is traversed, that is, if the critical is not found in the registers. But when it does, you use break to break the loop.

See an example:

import csv

critico = "Kenneth"

with open("data.csv") as file:
    reader = csv.reader(file, delimiter=';')
    for data in reader:
        if critico in data:
            print(data)
            break
    else:
        print("{} não está registrado no banco de dados".format(critico))
  

See working at Repl.it .

    
08.08.2017 / 22:20