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

Asked

Viewed 250 times

0

The first part that is to detect the position of the list I have already managed, the problem is at the time of Else, would like to know a method by which the Else is not printed together with the if.

Code and "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 -> https://repl.it/Jbl1/5

  • It depends on the structure of your file. Will the record always be unique, when it exists? Or can there be a situation where there is more than one record for the same critic? If you are interested, Python has a native library to work with CSV files.

  • The record will be unique always, just want to save the critics in some . csv even. I will read more about this library, but for now I want to do it in the same "primitive" way.

1 answer

1


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

The else of for is executed whenever the whole loop is traversed, ie if the critic is not found in the records. But when it is, you use the break to break the loop.

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

Browser other questions tagged

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