2016-01-18 20 views
0

我到目前为止有:如何输出文件中的每一行包含在列表中的任意字符串

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 

但是当我运行程序我还没有得到一个错误,什么也没有发生,它只是运行到下一行。 我会很感激任何帮助。 我想知道如果有一种方法来按数字顺序打印行或程序会自己在这里吗?

+0

你想去的地方不止一个匹配被发现,将被打印一次以上线路? – M4rtini

+0

不,我不想要任何重复 – DecafOyster208

回答

4

你没有得到输出,也没有错误,因为你不是遍历文件的行,而是遍历filename的字符。改变这一行:

for line in filename: 

这一个:

for line in filehandle: 
+0

它的工作!谢谢,但它输出重复,我将如何避免它们? – DecafOyster208

+0

@ DecafOyster208你的例子中的输出是'duplicating',因为你的items包含两个字符串('this'和'is'),它们都在第2行和第5行。如果你像这样运行你的函数:'FileSearch “textfile”,[“this”,“and”])',你会发现它没有重复。 但是如果你想在第一次匹配后停止循环,只需在'print(“%2i - %s”%(linenumber,line),end =“”)'语句后面添加'break'。 – vrs

+0

非常感谢你! – DecafOyster208

相关问题