0
I am creating a simple program that reads data from a file .txt
, passing them to a list. Then the program asks for a keyword to check if it exists in the list and show which position it is in.
A priori is giving to take the data from the file and pass to the list, but when it runs the code to search the keyword the code only works right when the keyword is at position 0 of the list. When it is in position 1 up, it no longer runs right, not finding the keyword even typing straight.
I made another file .py
with the same code, but with the list created in the code itself - without taking the data from the text file - and the program worked correctly, finding the position of any element that had in the list.
So I think the error is in the code that gets the file data .txt
and creates the list. But I have no idea what’s wrong, because I have already redone and tested this code several times and did not find the error.
Here’s the problematic code:
Lista = []
with open(Arquivo, 'r', encoding='UTF-8') as f:
Dados = f.readlines()
for linha in Dados:
for i in linha.split(','):
Lista.append(i)
print(Lista)
From what I see, the list creation is apparently normal, but the code that searches the keyword is not able to iterate across the list.
This is the code that searches for the keyword in the list:
for item in Lista:
print(item, Lista.index(item))
if item == Keyword:
print("Foi encontrada a palavra-chave na lista, na posição: ", Lista.index(Keyword))
Updating
I changed the search code to this one:
for item in Lista:
print(item, Lista.index(item))
if item != Keyword:
print('A palavra-chave não está na lista')
else:
print("Foi encontrada a palavra-chave na lista, na posição: ", Lista.index(Keyword))
Now I got the following answer:
Enter a list in format . txt: C: Users Suu Documents List of games.txt
['to']
['a', ' b']
['a', ' b', ' c']
['a', b', c', d']
Give a keyword: b
to 0
The keyword is not on the list
b 1
The keyword is not on the list
c 2
The keyword is not on the list
d 3
The keyword is not on the list
Process finished with Exit code 0
I don’t know what else to do, honestly... I think I’m really gonna give up. ='(
Updating
Anyone who wants to see the full code can access this link from my github: https://github.com/Suu021/Python-Projects-beginner/blob/Suu021-patch-1/Busca%20per%20Brute%20Force.py
And what is the content of the txt file?
– hkotsubo
Anyway, it can be simpler: https://repl.it/@hkotsubo/Ripecoolproject#main.py
– hkotsubo