14

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
  • 424
  • 1
  • 3
  • 15

2 Answers2

39

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
  • 14,790
  • 2
  • 28
  • 43
5

This is the top answer from a very similar question.

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