'Python - Why is the function not working when reading from file? [closed]

This is the code i have used

file


Solution 1:[1]

I think you meant to read all the lines from the file and look at the last one. Like this:

try:
    lines = myfile.readlines()
    GetTopic = lines[-1].strip()
    ...

Your code read one line into lines and lines[-1] was a single character and GetTopic = print(lines[-1]) meant that GetTopic was None and so not equal to any of your literal strings.

Solution 2:[2]

  • readline() returns a string - the first line of the document.
  • readlines() returns an array, which is probably what you're expecting.
    • I prefer to use lines = [x.strip() for x in myfile.readlines()]
  • The result of assigning a print() is always None. Python isn't the command line.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 BeRT2me