【发布时间】: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