[英]How to get line number in file opened in Python
I'm searching for a list of terms in a file.我正在搜索文件中的术语列表。 I want to print the line number in the file where the term was found.我想在找到该术语的文件中打印行号。
This is the code I'm using to find the term:这是我用来查找该术语的代码:
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)
In this case you could use enumerate
, which returns a tuple of an iterator count, and the value for the current iteration in your iterable variable (the filehandle f
in this case).在这种情况下,您可以使用enumerate
,它返回迭代器计数的元组,以及可迭代变量(在本例中为文件句柄f
)中当前迭代的值。
file_to_be_read.txt
: file_to_be_read.txt
:
Hello, this is line 0
And this is the second line
your_readscript.py
: your_readscript.py
:
with open('file_to_be_read.txt', 'r'):
for line_no, line in enumerate(f):
print(f'{line_no}: {line}')
Where line_no
now represents the current line number within the body of the for loop, starting at 0.其中line_no
现在表示 for 循环体中的当前行号,从 0 开始。
Output: Output:
0: This is line 0
1: And this is the second line
If you want it to start at 1 (or any other integer), you can pass that as argument to the start
parameter of enumerate
like so:如果您希望它从 1(或任何其他整数)开始,您可以将其作为参数传递给enumerate
的start
参数,如下所示:
for line_no, line in enumerate(f, start=1):
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.