Developer
Developer

Reputation: 123

How to search a particular string and content in a yaml file

Here below is my yaml file

    filename:
      #Name of the JMX files which needs to be executed
      - URLLogin.txt
      - URLupload.txt
      - XlsxFileUpload.txt

    URLLogin:
      - this is to test the script

    XlsxFileUpload:
      - this is to test the current script

I will be storing the filenames in an array. and call a method to get the file description in a loop. If the description is present for the filename it should return 1, else it should return zero

Here below is my code for searching the description.

#this method is to search a particular string in yaml
def searchStringInYaml(filename,string):
    with open(filename, 'r') as stream:
        content = yaml.load(stream)
        if string in content:
            print string
            return 1
        else:
            return 0
    stream.close()

Upvotes: 3

Views: 18398

Answers (2)

Sunitha
Sunitha

Reputation: 12015

If all you need is to check for a specified string in yaml file, dont parse the yaml file. Just read the file and check the contents

def searchStringInYaml(filename,string):
    with open(filename) as f:
        contents = f.read()
        return string in contents

Upvotes: 1

Rakesh
Rakesh

Reputation: 82765

yaml.load(stream) returns a dict use content.items() to iterate and check for value

Ex:

import yaml
with open(filename, 'r') as stream:
    content = yaml.load(stream)
    for k,v in content.items():
        if "URLLogin.txt" in v:
            print k, v

Output:

filename ['URLLogin.txt', 'URLupload.txt', 'XlsxFileUpload.txt']

Upvotes: 5

Related Questions