t_J
t_J

Reputation: 21

Trying to do an != option but failing

im tying to make an option to open a text file and the input can be with a .txt and the end and without. So far with the code i provided it works when i don't include a '.txt' but when i do it adds a '.txt' causing an error

if choice == 'r':
           fileName = input("Enter the file name: ")
           if fileName!= fileName.endswith('.txt'):
               fileName= fileName + '.txt'
               readEmployees(fileName)

readEmployees is used later to read the file and display names

Upvotes: 0

Views: 44

Answers (3)

Diggy.
Diggy.

Reputation: 6944

As the other answers have pointed out, the issue was with comparing a string to a boolean value:

>>> fileName = "file.txt"
>>> fileName
'file.txt'
>>> fileName.endswith(".txt")
True

Just a side-note: here's a more concise, although perhaps less easy on the eyes way of writing your code using a ternary operator:

if choice == "r":
    fileName = input("Enter the file name: ")
    fileName += ".txt" if not fileName.endswith(".txt") else ""
    readEmployees(fileName)

Read up about ternary operators here

Upvotes: 0

Sam Acquaviva
Sam Acquaviva

Reputation: 58

The endswith() method returns true or false. So, your if statement should just contain the endswith() method, and not compare it to the filename. Also, I'm guessing you want to call readEmployees(filename) regardless of if it ends with .txt. So, you should put it outside of your if statement because your current code only calls it if the file does not end with .txt.

if choice == 'r':
    fileName = input("Enter the file name: ")
    if not fileName.endswith('.txt'):
       fileName = fileName + '.txt'
    readEmployees(fileName)

Upvotes: 0

liorr
liorr

Reputation: 800

I cannot be sure without the desired output, but did you mean to write,

if choice == 'r':
           fileName = input("Enter the file name: ")
           if not fileName.endswith('.txt'):
               fileName= fileName + '.txt'
               readEmployees(fileName)

Basically, .endswith() returns a boolean, so you are comparing filename to a boolean.

Upvotes: 1

Related Questions