Read files in python

Asked

Viewed 129 times

0

good... I have a file with the following things :

if
else
(
)
'
"
print

and the following code :

arq = open('system/commands.txt','r')
arquivo = arq.readlines()
for l in range(0,7):
    print(arquivo[l])

palavra = input('Digite a palavra : ')

if palavra == arquivo[l]:
    print('certo !')

and wanted to know how I do when I type the word that is written in the file it appears the print('right'), in case the above command is not working and wanted to know why !

the command goes to the input part after nothing happens

  • 0 1 2 3 4 5 6 7, is inclusive range 0, stay smart.

1 answer

0


The problem is related to your variable l; It is defined by for:

for l in range(0,7):
    print(arquivo[l])

When this for executes, the variable l increasing 0 to 6 and the print will print the 7 lines of the file on the screen. Then the variable l used in the for will be with the last value she assumed, that is to say, 6.

Continuing the program, further down you make a comparison:

if palavra == arquivo[l]:

This line is comparing the typed word with the seventh word of the list arquivo, for the value of l is 6, which is the value left over in this variable at the end of the for above;

That is to say, arquivo[l] is equivalent to arquivo[6] (for the value of l at this point is 6) what is a reference to the word "print".

If you type the word print, will receive the message certo; if you type anything else you will not receive any message.

  • It worked, but in case as I would for it to read all the words of the file and if it is equal it runs the print?

  • @Hype for this you would have to compare with all the words in the file, and not only with one; there are several ways to do this, one of them would be to put the comparison within the for, another would be to use the operator in, etc.

Browser other questions tagged

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