Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string is in a file with Python [duplicate]

I'm new to Python and I'm trying to figure out how I can search for a string in a file and use it as a condition in a if clause: If "String" is in the file, Print("Blablabla")

like image 613
Gleyak Avatar asked Sep 23 '15 20:09

Gleyak


People also ask

How do you check if a string exists in a file in Python?

Method 1: Finding the index of the string in the text file using readline() In this method, we are using the readline() function, and checking with the find() function, this method returns -1 if the value is not found and if found it returns 0.

How do I verify a string in Python?

Method #1 : Using isinstance(x, str) This method can be used to test whether any variable is a particular datatype. By giving the second argument as “str”, we can check if the variable we pass is a string or not.

How do you find if a string is in another string Python?

Using find() to check if a string contains another substring We can also use string find() function to check if string contains a substring or not. This function returns the first index position where substring is found, else returns -1.


1 Answers

As you yourself said, just open the file and check if it is in it.

with open('myfile.txt') as myfile:
     if 'String' in myfile.read():
         print('Blahblah')

Isn't Python delightful?

like image 116
hspandher Avatar answered Oct 13 '22 07:10

hspandher