Create a function that reads a list correctly

-1

This function should ask for a name to be used as a search term. If the searched film is in the list, all the movie. Otherwise, a message that is not in the list should be shown.

This is the function I created to try to resolve the issue but it has some flaws that I quote below:

def funçao2(n):
    arq = open('ListaFilmes.txt', 'r')
    conteudo = arq.readlines()
    arq.close()

    n = str(input('Digite o nome do filme: '))

    for linha in conteudo:
        linha = linha.split(';')
        for coluna in linha:
            coluna = coluna.split()
            coluna1 = linha[0]
            coluna2 = linha[1]
            coluna3 = linha[2]
            coluna4 = linha[3]
            for elem in coluna:
                if n == elem:
                    print('NOME:',coluna1)
                    print('GÊNERO:',coluna2)
                    print('CLASSIFICAÇÃO:',coluna3)
                    print('ANO DE LANÇAMENTO:',coluna4)
                else:
                    print('O filme não consta na lista')

In this way I created, if for example I want to access a movie that appears in the list, it accesses the movie, but also shows the message 'The movie is not in the list', message that is only to happen if I try searching for a movie that is not on the list, and when I go looking for a movie that is not on the list, this message appears several times.

You can help me set the code so that if I look for the movie in the list, the program only shows the movie that was searched, and if I look for a movie that is not in the list, the program will show the message 'O movie not listed 'only once?

    
asked by anonymous 16.11.2018 / 01:34

1 answer

2

Since your file seems to be separated by a semicolon, I suggest that you use the csv module to read it instead of dividing lines manually.

To solve your problem, one of the most elegant ways is to use else in for :

import csv

pesquisa = input('Digite o nome do filme: ')

with open('ListaFilmes.txt', newline='') as f:
    cf = csv.DictReader(f, ['nome', 'genero', 'classificacao', 'ano'], delimiter=';')
    for filme in cf:
        if pesquisa in filme['nome']:
            print(filme['nome'], filme['genero'], filme['classificacao'])
            break
    else: # else do for
        print('O filme não consta na lista')

As you can see, else is aligned with for , so it will only run if the for loop reaches the end.

    
16.11.2018 / 01:52