Question

I am currently making a program that allows me to search for files in a user specified directory. But am having some trouble condensing down my try and except statements. 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

In each of these cases or overall, is there a better condensed way to write the above code? Each of the search functions return a list containing the result of the code.

Was it helpful?

Solution

I have a couple of suggestions:

1. Improve indenting.

At the top of your file you have:

if os.path.exists(file_path)!= True:
    print('\n******* Path does not exist. *******\n')       

    else:

The else statement has to have the same indentation value as the original if.

2. Remove newlines

As you are concerned about taking space up, just remove all the newlines. I would not suggest this because your code can become confusing to read, but if you are a stickler about space, go ahead. I can count 11 newlines, so if you remove those, you've removed 15th of your file.

3. Be pythonic

If you care about the lines your code is taking up, try to be as pythonic about each line as possible, for future review/editing. Instead of if x in 'Ss': to check if x is an s or S, just do if x.lower() == 's':

4. Format try... except

Your try... except's encompass most of your code. Try to only limit them to the line that may raise the error. Here's an example:

try:
    var = int(raw_input())
    x = float(var)/100.0
    if x == 1:
        print 'YAY'
    else:
        print 'BOO!'
    for k in range(1, x):
        print 'this has looped %d times' %(k)
except ValueError:
    print 'Your input is not in a number format!'

In this code, we want to make sure that the input is a number. However, that can only be checked by the first line, and everything else is rubbish. So just surround the first line, and leave the rest untouched.

Note:

Do not remove necessary components from your try... except's, or some arbitrary error may be raised.

5. Shrink your while loops

Instead of doing the following code:

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

You can do

size = input('\nPlease enter file size: ')
while size.isdigit() == False or not rr = search_by_size(size, file_path):
    size = input('\nPlease enter file size: ')

Your edited code: Original: 59 lines; Edited: 33 lines:

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.lower() == 'n':
            name = input ('\nEnter file name: ')
            try:
                while not search_by_name(name, file_path):
                    name = input ('\nEnter file name: ')
            except WindowsError:
                print('\n***** Oops! Access denied.*****\n')
                continue
        elif answer .lower() == 'e':
            ending = input ('\nEnter the file extension: ')
            try:
                while not search_by_extention(ending, file_path):
                    ending = input ('\nEnter the file extension: ')
            except WindowsError:
                print('\n***** Oops! Access denied. *****\n')
                continue
        elif answer.lower() == 's':
            size = input('\nPlease enter file size: ')
            try:
                while size.isdigit() == False or not search_by_size(size, file_path):
                    size = input('\nPlease enter file size: ')
            except WindowsError:
                print('\n***** Oops! Access denied. *****\n')
                continue
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top