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")
            Asked
            
        
        
            Active
            
        
            Viewed 9.4k times
        
    2 Answers
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
- 
                    1If I'm not mistaken, we can use "open('myfile.txt', 'r')" in order to only reading the file, and avoiding the ".read()" ahead. – munizig Nov 25 '20 at 00:59
- 
                    Is it possible to ignore case? – Ferdossi Feb 15 '21 at 14:48
- 
                    2@Ferdossi just do 'String'.lower() in myfile.read().lower() – hspandher Feb 15 '21 at 15:19
7
            
            
        This is the top answer from a very similar question.
if 'blabla' in open('example.txt').read():
    print "true"
- 
                    1
- 
                    1
- 
                    1@SrgSprinkles I'm guessing it didn't work because this answer is Python 2 where the first answer is Python 3. You have to call the right binary. print"" and print() are not interchangeable between versions – MGoBlue93 Aug 02 '20 at 04:36
 
     
    