到目前为止,我所拥有的:
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")
我正在尝试打印包含列表“items”中包含的任何字符串的行号前的行。所以它会输出如下内容:
>>>FileSearch("textfile",["this","and","is"])
2 - this is the 2nd line
4 - hello and goodbye
5 - this is a very basic example
但是当我运行程序时,我甚至没有收到错误,什么也没有发生,它只是运行到下一行。 我非常感谢你的帮助。 我还想知道是否有一种方法可以按数字顺序打印行,或者程序会自己在这里打印行吗
您没有得到输出,也没有得到错误,因为您不是在文件的行上进行迭代,而是在
filename
的字符上进行迭代。更改此行:对于这一点:
相关问题 更多 >
编程相关推荐