Python Forum
Test a file for a string without opening it? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Test a file for a string without opening it? (/thread-27339.html)



Test a file for a string without opening it? - tester_V - Jun-03-2020

Hi,
I have a lot of files in a directory,
Is there any good way to test a file for a string without opening it?
String =’Run Time’
If string is in file :
	do something
I hear about a function ”any” but not sure how to use it, or maybe there is a better way?

thank you in advance!


RE: Test a file for a string without opening it? - ndc85430 - Jun-03-2020

You need to read the file if you want to know what's in it.


RE: Test a file for a string without opening it? - tester_V - Jun-03-2020

I was thinking to use a "break" if the first 'Run Time" line found.
Then reload the file again and process it to the end of the file.
something like this:
                with open(currentF) as mfiler:  
                    for ln in mfiler:
                        if runtime_l in ln :
                            ln=ln.rstrip()
                            print ("Run Time line FOUND__>", ln)
                            ftoiter = currentF                            
                            break 

                    with open(ftoiter) as mfile:  
                        for lns in mfile:
                            if runtime_l in lns :
                                print ("RUN TIME line++++++++++++++ >", lns)
                                print (lns)