【问题标题】:Python search file and print line if matches anything in array如果匹配数组中的任何内容,Python 搜索文件并打印行
【发布时间】:2017-09-28 15:40:19
【问题描述】:

我有一个包含多个字符串的数组。我需要搜索文件以查看文件中的任何行是否与数组中的任何字符串匹配并打印文件中匹配的所有行

这是我目前所拥有的,但我的 python 语法/逻辑有点偏离

under30=[] is the array of multiple strings i want to match against the file 
with open("list.txt") as f2:
        for line in f2:
                if under30() in line:
                        print line

【问题讨论】:

    标签: python arrays file


    【解决方案1】:

    假设under30 是您要从文件中匹配的字符串列表

    if under30() in line:

    应该是:

    if line in under30:

    【讨论】:

      【解决方案2】:

      你可以试试这个:

      file_data = [i.strip('\n') for i in open('filename.txt')]
      under30=["string1", "string2", "string3"]
      final_lines = [i for i in file_data if i in under30]
      

      【讨论】:

        猜你喜欢
        • 2020-06-12
        • 1970-01-01
        • 1970-01-01
        • 2013-03-21
        • 1970-01-01
        • 2021-09-11
        • 1970-01-01
        • 2017-11-25
        • 2012-07-25
        相关资源
        最近更新 更多