2

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
Andrew
  • 307
  • 7
  • 13

3 Answers3

2

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")
Jab
  • 26,853
  • 21
  • 75
  • 114
1

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")
nullromo
  • 2,165
  • 2
  • 18
  • 39
Jab
  • 26,853
  • 21
  • 75
  • 114
1

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
nullromo
  • 2,165
  • 2
  • 18
  • 39
  • 1
    This worked to check every single line perfectly! I only need the very last line but this was very helpful – Rrezon Beqiri May 17 '21 at 17:53
  • If you just want to look at the last line, you could use some of the code in the other answers. Keep in mind there are performance tradeoffs at play here. Take a look at this answer: https://stackoverflow.com/a/54278929/4476484 and note that reading the whole file with `readlines` would probably not be recommended for a very large file. Also, when using `file.readlines()[-1]`, you may run into an issue if the last line of the file is blank. Based on your application, you may want to ignore any potential last blank lines or you may not. Just something to be aware of. – nullromo May 17 '21 at 18:01