19

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")

Gleyak
  • 474
  • 1
  • 3
  • 15

2 Answers2

47

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?

hspandher
  • 15,934
  • 2
  • 32
  • 45
7

This is the top answer from a very similar question.

if 'blabla' in open('example.txt').read():
    print "true"
Community
  • 1
  • 1
camden
  • 1,908
  • 19
  • 18