Python 如何在yaml文件中搜索特定字符串和内容
下面是我的yaml文件Python 如何在yaml文件中搜索特定字符串和内容,python,python-2.7,yaml,Python,Python 2.7,Yaml,下面是我的yaml文件 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
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
我将把文件名存储在一个数组中。并调用一个方法来获取循环中的文件描述。如果文件名有描述,则应返回1,否则应返回零
下面是我搜索描述的代码
#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()
yaml.load(stream)
返回dict usecontent.items()
以迭代并检查值
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
filename ['URLLogin.txt', 'URLupload.txt', 'XlsxFileUpload.txt']
输出:
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
filename ['URLLogin.txt', 'URLupload.txt', 'XlsxFileUpload.txt']
如果您只需要检查yaml文件中的指定字符串,请不要解析yaml文件。只需阅读文件并检查内容
def searchStringInYaml(filename,string):
with open(filename) as f:
contents = f.read()
return string in contents
yaml.load
返回字典。上校不是凯普托凯。如果删除冒号,则无法搜索字符串。它只返回零总是@cricket_007内容中的字符串
只检查字典的键,没有任何值显示来检查值@不清楚你在找什么。您是绝对需要解析yaml,还是只需要检查文件是否包含字符串
?如果是后者,则可以返回1 If string in open(filename).read()else 0