【问题标题】:How to output each line in a file which contains any of the strings in a list如何输出包含列表中任何字符串的文件中的每一行
【发布时间】:2016-04-23 14:38:12
【问题描述】:

到目前为止我所拥有的:

def FileSearch(filename, items):
    try:
        filehandle = open( filename, "r" )
        linenumber = 0
        for line in filename:
            linenumber +=1
            for item in items:
                if item in line:
                    print("%2i - %s" %( linenumber, line), end="")
    except IOError:
        print("Error file cannot be read or file does not exist")
        print("Please try again")

我正在尝试打印行,以行号开头,其中包含列表“项目”中包含的任何字符串。所以它会输出如下内容:

>>>FileSearch("textfile",["this","and","is"])
2 - this is the 2nd line
4 - hello and goodbye
5 - this is a very basic example

但是当我运行程序时,我什至没有收到错误,什么也没发生,它只是运行到下一行。 我会很感激任何帮助。 我还想知道是否有办法按数字顺序打印行,或者程序会在这里自己做吗?

【问题讨论】:

  • 您是否希望多次打印找到多个匹配项的行?
  • 不,我不想要任何重复

标签: python exception file-io io filehandle


【解决方案1】:

你没有得到输出,也没有错误,因为你不是在文件的行上迭代,而是在filename的字符上迭代。更改此行:

for line in filename:

到这个:

for line in filehandle:

【讨论】:

  • 成功了!谢谢,但它输出重复,我将如何避免它们?
  • @DecafOyster208 示例中的输出是“重复”,因为您的 items 包含两个字符串(thisis),它们都在第 2 行和第 5 行。如果您运行像这样的函数:FileSearch("textfile",["this","and"]),你会发现它没有重复。但如果你想在第一次匹配后停止循环,只需在print("%2i - %s" %( linenumber, line), end="") 语句后添加break
猜你喜欢
  • 2021-06-09
  • 2014-10-08
  • 2020-08-09
  • 1970-01-01
  • 1970-01-01
  • 2018-03-06
  • 2020-07-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多