比使用try和except更好的格式

时间:2014-04-17 02:12:18

标签: python-3.x try-except

我目前正在制作一个程序,允许我在用户指定的目录中搜索文件。但是在缩小我的tryexcept语句时遇到了一些问题。我目前的代码如下:

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

在每种情况下或整体而言,是否有更好的浓缩方式来编写上述代码?每个搜索函数都返回一个包含代码结果的列表。

1 个答案:

答案 0 :(得分:1)

我有几点建议:

1。改进缩进。

在文件的顶部,您有:

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

    else:

else语句必须与原始if具有相同的缩进值。

2。删除换行符

由于您担心占用空间,只需删除所有换行符即可。我不建议这样做,因为你的代码可能会让人感到困惑,但是如果你是一个关于太空的坚持者,请继续。我可以计算11个换行符,所以如果你删除它们,你已经删除了你的 1 / 5 th 文件。

3。是pythonic

如果您关心您的代码正在占用,请尝试尽可能地对每行进行pythonic,以便将来进行审核/编辑。不是if x in 'Ss':来检查xs还是S,而是if x.lower() == 's':

4。格式try... except

您的try... except包含大部分代码。尽量只将它们限制在可能引发错误的行。这是一个例子:

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!'

在此代码中,我们要确保输入是一个数字。但是,只能通过第一行检查,其他一切都是垃圾。所以只围绕第一行,其余部分不受影响。

注意:

请勿从try... except删除必要的组件,否则可能会引发任意错误。

5。缩小while循环

而不是执行以下代码:

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

你可以做到

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: ')

您编辑的代码:原文:59行; 已编辑:33行

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