Вы можете добавить exception FileNotFoundError:
и continue
в цикле:
def checkInt(val):
try:
val = int(val)
return val
except:
print('Not a valid integer')
def main():
print('Hi welcome to the file processor')
while 1:
val = checkInt(input('''Selection Menu:
0. Exit program
1. Read from a file
'''))
if val == 0:
print('goodbye')
exit()
elif val == 1:
fileName = input('Enter a file name: ')
checkInt()
inFile = open(fileName, 'r')
print(inFile.read())
inFile.close
ВЫХОД :
Hi welcome to the file processor
Selection Menu:
0. Exit program
1. Read from a file
1
Enter a file name: blahblah
Not a valid file.
Selection Menu:
0. Exit program
1. Read from a file
1
Enter a file name: hey.txt
5,7,11,13,17,19,23,29,31,37,41,43,47,
Selection Menu:
0. Exit program
1. Read from a file
РЕДАКТИРОВАТЬ :
вы можете сделать то же самое в методе checkFile
, просто позвоните своему main()
:
def checkFile(fileName):
try:
File = open(fileName)
File.close
except FileNotFoundError:
print('Not a valid file.')
main()