Python的try except无法正常工作

3
# Test your program with the following:
# Case 1: When the user inputs 84, the program should delete the file 84.txt
# Case 2: When the user inputs 84 (again), the program should print a File Not Found error message
# Case 3: When the user inputs 5, the program should delete the file 5.txt
#TODO: Your code goes here
def FileDel(x):
    path = "/home/nbuser/library/parent_dir/files_exercises"
    ls = os.listdir(path)
    for i in ls:
        if x==i:
            os.remove(i)
            print(x,"removed")
        elif x.isdigit():
            x1=x+".txt"
            if x1==i:
                os.remove(i)
                print(x1,"removed")
        else:
            try:
                os.remove(i)
            except FileNotFoundError as exception_object:
                print("Cannot find file: ", exception_object)
            except PermissionError as exception_object:
                print("Cannot delete a directory: ", exception_object)
            except Exception as exception_object:
                print("Unexpected exception: ", exception_object)
                c_path = os.path.join(path, i)              


x=input("enter a file no. that you want to del,e.g. 5 or 5.txt: ")                    
FileDel(x)

enter a file no. that you want to del,e.g. 5 or 5.txt: 88
88.txt removed
Unexpected exception:  [Errno 21] Is a directory: 'dir_1'

上面的指令要求先删除文件,然后第二次删除相同文件时会返回文件未找到。但是我的代码第一次将所有内容打印在一起,第二次删除时打印如下:
enter a file no. that you want to del,e.g. 5 or 5.txt: 88
Unexpected exception:  [Errno 21] Is a directory: 'dir_1'

请帮忙!


1
你的代码缩进正确吗?我看到一个for循环与一个else语句匹配。 - Jim Nilsson
1
存在 for/else http://book.pythontips.com/en/latest/for_-_else.html - Joe
我明白了,你每天都会学到新的东西。 - Jim Nilsson
1个回答

2

我会用稍微不同的方式编写代码:

def FileDel(x):
    path = "/home/nbuser/library/parent_dir/files_exercises"
    ls = os.listdir(path)
    try:
        if str(x).isdigit():
            os.remove(path + '\\' + str(x) + ".txt")
            print(x, "removed")
        else:
            os.remove(path + '\\' + str(x) )
            print(x, "removed")

    except OSError as exception_object:
        print("Cannot find file: ", exception_object)
    except PermissionError as exception_object:
        print("Cannot delete a directory: ", exception_object)
    except Exception as exception_object:
        print("Unexpected exception: ", exception_object)
        c_path = os.path.join(path, i)


x=raw_input("enter a file no. that you want to del,e.g. 5 or 5.txt: ")
FileDel(x)

您可以使用os.path.exists(path)来提前判断路径或文件是否存在。

在我将 '\' 改为 '/' 后,它完美地工作了,非常感谢! - Karen Jiang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接