簡體   English   中英

如何獲取在 Python 中打開的文件中的行號

[英]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(或任何其他整數)開始,您可以將其作為參數傳遞給enumeratestart參數,如下所示:

for line_no, line in enumerate(f, start=1):
    ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM