从属性文件中搜索字符串并在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)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...