[英]How to get line number in file opened in Python
我正在搜索文件中的术语列表。 我想在找到该术语的文件中打印行号。
这是我用来查找该术语的代码:
w = "wordlist.txt"
d = "demofile.txt"
keys = [key for key in (line.strip().lower() for line in open(w)) if key]
with open(d) as f:
print("File", w)
for line in f:
for key in keys:
if key in line.lower():
print(key)
在这种情况下,您可以使用enumerate
,它返回迭代器计数的元组,以及可迭代变量(在本例中为文件句柄f
)中当前迭代的值。
file_to_be_read.txt
:
Hello, this is line 0
And this is the second line
your_readscript.py
:
with open('file_to_be_read.txt', 'r'):
for line_no, line in enumerate(f):
print(f'{line_no}: {line}')
其中line_no
现在表示 for 循环体中的当前行号,从 0 开始。
Output:
0: This is line 0
1: And this is the second line
如果您希望它从 1(或任何其他整数)开始,您可以将其作为参数传递给enumerate
的start
参数,如下所示:
for line_no, line in enumerate(f, start=1):
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.