2

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) 
3
  • 3
    Use enumerate: for lineno, line in enumerate(f):. Keep in mind that this starts numbering from 0. Commented May 21, 2021 at 12:48
  • 1
    @9769953 - you can use start parameter to start from where you want Commented May 21, 2021 at 12:52
  • @DonKnacki Thanks! All these years using enumerate, to never know about the start parameter (because I never had to look up the documentation for enumerate). Commented May 21, 2021 at 12:54

1 Answer 1

3

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).

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}') 

Where line_no now represents the current line number within the body of the for loop, starting at 0.

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:

for line_no, line in enumerate(f, start=1): ... 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.