I am currently writing a program that allows me to search for files in a user-specified directory. My current code is as follows:
if os.path.exists(file_path)!= True:
print('\n******* Path does not exist. *******\n')
else:
while True:
aa = '''\nWhich search characteristics would you like to use? \n 1. Search by name: N \n 2. Search by extension: E \n 3. Search by size: S
\n Please enter your choice: '''
answer = input(aa).strip()
if answer not in 'NnEeSs' or answer=='':
print('\n***** Invalid choice. *****')
elif answer in 'Nn':
while True:
try:
name = input ('\nEnter file name: ')
rr = search_by_name(name, file_path)
if not rr:
print('\n***** File not found *****\n')
else:
break
except WindowsError:
print('\n***** Oops! Access denied.*****\n')
continue
elif answer in 'Ee':
while True:
try:
ending = input ('\nEnter the file extension: ')
rr = search_by_extention(ending, file_path)
if not rr:
print('\n***** No File(s) found *****\n')
else:
break
except WindowsError:
print('\n***** Oops! Access denied. *****\n')
continue
elif answer in 'Ss':
while True:
try:
size = int(input('\nPlease enter file size: '))
rr = search_by_size(size, file_path)
if not rr:
print('\n***** No file(s) found *****\n')
else:
break
except ValueError:
print('\n***** Enter an numeric value. *****\n')
continue
except WindowsError:
print('\n***** Oops! Access denied. *****\n')
continue
Each of the search functions returns a list containing the result.
The try
and except
statements are concerning, and I feel they can be improved.
In each of these cases, or generally, how can the code be improved, or simplified?