Forum Discussion

IuliaVascan's avatar
IuliaVascan
Occasional Contributor
3 years ago
Solved

Finding a word in txt file - Script TestComplete using Python

HI there,

 

I have this code in Python (it's working, it looks in a txt file for the word "Error" and when it's finding the word it's printing the line):

 

 

filename = 'C:/Users/VAI3CLJ/Workspaces/error.log'

def search(filename, text):
with open(filename) as f:
   for line in f:
      if text in line:
         yield line

if __name__ == '__main__':
   for result in search(filename, 'Error'):
      print(result)

 

 

 But I cannot figure it out, why when I am moving the code in TestComplete Script (Python) it's no working. Here is the TestComplete Script:

 

 

def search_error():
   filename = ProjectSuite.Path+"error.log"  
   def search(filename, text):
      with open(filename) as f:
         for line in f:
            if text in line:
               yield line
   if __name__ == '__main__':
      for result in search(filename, 'Error'):
         Log.Message(result)

 

 

Thank you for your kind help!

  • maybe its the classic python notation thats throwing the script editor off

    if __name__ == '__main__':

     

    so since its doing nothing but calling the functions into action, commented it out, and matched the indentation levels (using your code, the below should retain the format if you want to copy and paste, just replace the path to your file)

    def test4():
      
      filename = 'C:\\Users\\justin.kim\\Desktop\\log.txt'
    
      def search(filename, text):
        with open(filename) as f:
         for line in f:
            if text in line:
               yield line
    
      #if __name__ == '__main__':
      for result in search(filename, 'Error'):
        Log.Message(result)

     

     

3 Replies

  • maybe its the classic python notation thats throwing the script editor off

    if __name__ == '__main__':

     

    so since its doing nothing but calling the functions into action, commented it out, and matched the indentation levels (using your code, the below should retain the format if you want to copy and paste, just replace the path to your file)

    def test4():
      
      filename = 'C:\\Users\\justin.kim\\Desktop\\log.txt'
    
      def search(filename, text):
        with open(filename) as f:
         for line in f:
            if text in line:
               yield line
    
      #if __name__ == '__main__':
      for result in search(filename, 'Error'):
        Log.Message(result)