How to use the conditions with the contents of a txt file in python [closed]

-2
data = open("archivo.txt", "r")
o_data = data.readlines()
data.close()
if "hola" == o_data[2]:
    print("si")
else:
    print("no")

The problem is that I do not know if the word hello is equal to the hello that is written in the file. Thanks for the help:)

    
asked by Ramphy Aquino Nova 05.08.2017 в 19:17
source

1 answer

1

This is your code:

data = open("archivo.txt", "r")
o_data = data.readlines()
data.close()
if "hola" == o_data[2]: # Según tú, qué debería hacer o_data[2]? 
   print("si")
else:
   print("no")

A couple of clarifications:

readlines () allows you to read the content in a list of lines. Having that list of lines, what you want to do is read line by line and see if there is at least one line that contains the word "hello". When you find at least one line that meets that condition, you want it to print "yes". I propose the following solution:

data = open("archivo.txt", "r")
o_data = data.readlines()
for line in o_data: # Iterador que permite revisar cada línea de texto
    if "hola" in line: 
        print("si")
    else:
        print("no")
data.close() # El archivo se debe cerrar siempre al final.

I hope the explanation will help. It is the least that can be done without having an idea of how your file looks and without understanding the question very well.

    
answered by 07.08.2017 в 17:14