0

Here is a function in my code, I have a previously written file called numbers.txt . I am trying to read that file should they enter numbers or numbers.txt. However, it prints the file no matter what input is entered.

userfile = input('Please enter file name: ')
if userfile == 'numbers' or 'numbers.txt':
    f = open('numbers.txt','r')
    for line in f:
       print(line)
else:
    print('Sorry, this file does not exist')
Yassine Faris
  • 951
  • 6
  • 26

2 Answers2

0

The problem is this line:

if userfile=='numbers' or 'numbers.txt':  # After the or

In python a string is True if it's not empty ('') so 'numbers.txt' is True. Change it to :

if userfile == 'numbers' or userfile == 'numbers.txt':
Yassine Faris
  • 951
  • 6
  • 26
0
userfile=input('Please enter file name: ')
if (userfile=='numbers') or (userfile=='numbers.txt'):
    try:
        f=open('numbers.txt','r')
    except:
        print('Sorry, this file does not exist')
        exit()
    for line in f:
       print(line)
else:
    print('Sorry, this file does not exist')
Mika72
  • 413
  • 2
  • 12