Rrezon Beqiri
Rrezon Beqiri

Reputation: 41

Check if the very last element of a list matches a string of choice

This sounds like it has been asked before but I cannot find anything that helps me.

My code is:

with open('file directory', 'r') as file:
data = []

for line in file:

    for word in line.split():
        data.append(str(word))
        last_word = str(data[-1])
        if last_word == "bobby":
            print("yes")
        else:print("no")

I want to know if the last element of the text file which I turned into a list matches a string, for example "bobby". Instead, what I get is basically a counter of how many times bobby was mentioned in the list.

Terminal:

yes
yes
yes

Upvotes: 2

Views: 280

Answers (3)

Jab
Jab

Reputation: 27515

Instead of looping the file just turn it into a list and grab the last element. You're very close just the loop is unnecessary:

with open('file directory', 'r') as file:
    data = file.readlines()
    last_word = data[-1].split()[-1]
    if last_word == "bobby":
        print("yes")
    else:
        print("no")

Upvotes: 1

Bernardo Trindade
Bernardo Trindade

Reputation: 481

How about:

with open('file directory', 'r') as file:
     last_line = f.readlines()[-1]
     print("yes" if last_line == "bobby" else "no")

or if you want to be short and cryptic:

with open('file directory', 'r') as file:
     print("yes" if f.readlines()[-1] == "bobby" else "no")

Upvotes: 2

nullromo
nullromo

Reputation: 2647

If you want to look for the last word of each line, this works.

with open('asdf.txt', 'r') as file:
    for line in file:
        words = line.split()
        try:
            if words[-1] == "bobby":
                print("yes")
            else:
                print("no")
        except:
            # blank line
            pass

Upvotes: 1

Related Questions