the program does not read the file line it should read

Asked

Viewed 56 times

0

i am making a program q reads a specific line from a.txt file so that I can then separate the line and get the information. i did this function to know on which line the CPF that was typed is located

def get_line(word):
    with open('alunos.txt') as alunos:
        for l_num, l in enumerate(alunos, 1): 
            if word in l: 
                return l_num
        return False 

the file "students.txt" has information like this:

nome do aluno 1,CPF,Semestre de ingresso
nome do aluno 2,CPF,Semestre de ingresso
...

here’s another part of the code:

cpf = input("\nDigite o CPF do aluno: ")

with open('alunos.txt') as alunos:
    for line in alunos:
        if cpf in line:

            posicao = int(get_line(cpf))
            
            inf = alunos.readlines()[posicao]
            #text = inf.split(',')  
            print(inf)
            break
    else:
        print("CPF não cadastrado\n")

the problem I get is this: when I type Cpf q is on the first line of the file, it returns the third line. and if I type any other Cpf just gives error... if I give a print on the variable "position" it returns the number of the right line, but when I read using readlines() this problem happens

1 answer

2


The problem is you call readlines afterward of having read the first line (when you do for line in alunos, every iteration of for a line is read). That is, the first line has already been read, and there you call readlines, only that as the first line has already been read, the result will be a list containing the second line onwards (that is, the first element is the second line, the second element is the third line, etc).

And how get_line returned 1, you try to take the second element of this list (because lists are indexed to zero: the first element is at index zero, the second at index 1, etc).


In fact you are complicating for nothing. If you are already reading the file on for line in alunos, do not need to open the file again in function get_line. You don’t really need this function, you can do it all at once:

cpf_busca = input("\nDigite o CPF do aluno: ")

with open('alunos.txt') as alunos:
    # itera pelas linhas do arquivo, juntamente com o número da linha
    for num, linha in enumerate(alunos, 1):
        # se quiser, pode separar os campos
        nome, cpf, semestre = linha.strip().split(',')
        if cpf == cpf_busca:
            print(f'CPF {cpf_busca} encontrado na linha {num}')
            break
    else:
        print("CPF não cadastrado\n")

I also used strip() to remove the line break and split to separate the fields (but if you want, you can continue using if cpf in linha).

Browser other questions tagged

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