简体   繁体   中英

For loop in Python and reading input from file

I'm trying to figure out why I get multiple return results for the else statement. I am trying to read from a file. The user will enter something and if that something matches a word or a sentence/number in file print out that line. It works fine if the word is found inside the file. The file contents print out for the matched word in the document. But my issue concerns the else statement. If the word is not in the document, it prints out every line with the else's print statement. I do understand I have it inside a for loop and it will iterate all instances of the lines in the file. My end goal is just to have one instance of the else statements print out, not on every line.

file=open('new_file.txt','r')
new_user=input(str('NEW: '))
for line in file:
    line=str(line)
    if new_user in line:
        print('yes its in here: ',line)
    else:
        print('Word: ',new_user,' not in here')
file.close()

Output without (else statement), prints out correct line found in document:

NEW: danny yes its in here: 10101 does he know does he know. danny

Output WITH (else): prints out all lines that dont match. I just want to print out one instance of the statement thats in the else block:

NEW: dude

Word: dude not in here

Word: dude not in here

Word: dude not in here

Word: dude not in here

Word: dude not in here

Word: dude not in here

Word: dude not in here

Word: dude not in here

Word: dude not in here

Word: dude not in here

Word: dude not in here

Word: dude not in here

Word: dude not in here

Word: dude not in here

Word: dude not in here

Word: dude not in here

Word: dude not in here

Word: dude not in here

Output with else statement entering matching name in document:

NEW: danny

Word: danny not in here

Word: danny not in here

Word: danny not in here

Word: danny not in here

Word: danny not in here Word: danny not in here

Word: danny not in here

Word: danny not in here

yes its in here: 10101 does he know does he know. danny

Word: danny not in here

Word: danny not in here

Word: danny not in here

Word: danny not in here

Word: danny not in here

Word: danny not in here

Word: danny not in here

Word: danny not in here

Word: danny not in here

Any help in the right direction would be great.

Thanks, Danny

Set a flag and print it when you're finished checking the file.

file=open('new_file.txt','r')
new_user=input(str('NEW: '))
flag = False
for line in file:
    line=str(line)
    if new_user in line:
        print('yes its in here: ',line)
        flag = True
if not flag:
    print('Word: ',new_user,' not in here')
file.close()

Another option instead of using a flag is to enclose this logic within a function, and and return the line if the word is found or return None if it was never found.

def find_word (file, word):
    with open(file) as infile:
        for line in infile:
            if word in line:
                return line
    return None

new_user=input(str('NEW: '))
ln = find_word('new_file.txt', new_user)

if (ln):
    print('yes its in here: ',ln)
else:
    print('Word: ',new_user,' not in here')

Explanation:

By returning inside the function as soon as a match is found, you ensure that it will only ever return the 1st instance of the keyword you're looking for.

In switching to opening the file using the with open('filename') as ... syntax, you gain the advantage that if an exception is thrown while reading the file, the file will still be closed. And it will also close the file before returning. Your current method of first opening the file using file=open(...) and then at the very end closing it explicitly using file.close() means that there are certain circumstances where the file will not be properly closed. (which might not be a problem here, but could be in the future)

Another advantage is that turning your code into function makes it easier to run the query multiple times, using different search keywords.

You have to use like a flag, something that shows you if you matched the word. For example:

file=open('new_file.txt','r')
new_user=input(str('NEW: '))
notFound = 1 # The flag that shows if the user was found.
for line in file:
    line=str(line)
    if new_user in line:
        print('yes its in here: ',line)
        notFound = 0 # Now is false.
if notFound: # Check if the user wasn't found.
    print('Word: ',new_user,' not in here')
file.close()

I think that should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM