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")
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.
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.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With