如何解决从属性文件中搜索字符串并在Python中打印行
如果字符串与列表中的字符串匹配,我将尝试打印文件的行。
步骤1 - 我正在从db作为txt文件获取帐户/用户列表,内容将如下所示
list_from_db.txt
userA
userB
userC
我首先使用以下代码将此.txt文件转换为列表-
lineList = [line.rstrip('\n') for line in open("list_from_db.txt")]
print(lineList)
输出-
['userA','userB','userC']
步骤2 -
现在我正在使用属性文件搜索此字符串列表,内容将如下所示
user.properties
GIT_url = https://giturl:9000
url_usercontent= redirection
value.userB.duplicate=yes
checkif.userC.exist=on
我的代码,以检查列表中的内容是否存在于该文件中-
with open("user.properties") as f:
file_content = f.read()
#lineList is a list which i am taking from Step #1
for x in lineList:
if x in file_content:
print(x)
我的输出-
userB
userC
我能够打印匹配的字符串,但是我需要属性文件中的整行。
预期产量-
value.userB.duplicate=yes
checkif.userC.exist=on
编辑#1(边缘情况)- 如果我的列表中包含字符串“ user”,则它应仅考虑该值而不是相对值。
例如:如果我有这样的列表-
['user','userA','userC']
它不应从列表中显示与“用户”相关的所有输出-
它仍然应该给我上述预期的输出-
value.userB.duplicate=yes
checkif.userC.exist=on
它不应该这样打印输出-
url_usercontent= redirection
value.userB.duplicate=yes
checkif.userC.exist=on
请帮助。
解决方法
类似的事情应该起作用。
users=['userA','userB','userC']
with open('user.properties') as f:
file.content = f.read()
contents = file_content.split('\n')
for content in contents:
for user in users:
if ('.'+user+'.') in content:
print(content)
,
尝试
with open(text,'r') as f:
content1 = f.readlines()
content2 = [x.strip() for x in content1]
pattern = "my_pattern"
for z in content2:
if pattern:
print(z)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。