2

I have a list 'a',where I need to print all the matching letters of the list with the line of a text file 'hello.txt'.But it only prints the first word from the list and line instead of all the list and lines

a=['comp','graphics','card','part']

with open('hello.txt', 'r') as f:
    for key in a:
        for line in f:
            if key in line:
                print line, key

It results as:

comp and python
comp

Desired output:

comp and python
comp
graphics and pixel
graphics
micro sd card
card
python part
part

Please help me to get desires output.Answers willbe appreciated!

1 Answer 1

7

The file-object f is an iterator. Once you've iterated it, it's exhausted, thus your for line in f: loop will only work for the first key. Store the lines in a list, then it should work.

a=['comp','graphics','card','part']
with open('hello.txt', 'r') as f:
    lines = f.readlines()  # loop the file once and store contents in list
    for key in a:
        for line in lines:
            if key in line:
                print line, key

Alternatively, you could also swap the loops, so you iterate the file only once. This could be better if the file is really big, as you won't have to load all it's contents into memory at once. Of course, this way your output could be slights different (in a different order).

a=['comp','graphics','card','part']
with open('hello.txt', 'r') as f:
    for line in f:     # now the file is only done once...
        for key in a:  # ... and the key loop is done multiple times
            if key in line:
                print line, key

Or, as suggested by Lukas in the comments, use your original loop and 'reset' the file-iterator by calling f.seek(0) in each iteration of the outer key loop.

Sign up to request clarification or add additional context in comments.

2 Comments

Or alternatively, use f.seek(0) to reset the cursor to the starting position for every term in a.
@user3830379 readlines isn't really the important aspect of tobias' answer. "You will exhaust iterators as you consume them" is the important part to take home. For most other use cases, your for line in f: is absolutely correct and the best way to iterate over files line by line, and should be preferred over readlines()!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.