python尝试除了不工作

标签 python exception try-except

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

请帮忙!

最佳答案

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

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) 提前告诉你路径/文件是否存在

关于python尝试除了不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51980564/

相关文章:

python - 装饰图案与 Python 中的猴子修补

python - 如何在用户输入错误时重新加载具有无效表单的页面

python - Python 字符串是否以终止 NULL 结尾?

c# - EF 中的常量导致异常

delphi - 为什么在明显的 "safe"代码中使用异常处理?

python - 如何在Python中读取串口时中断while循环

python - Python 的可点击图像

java - 如何使用 Java 中的自定义异常处理无效数据行?

java - 在不使用 instanceof 的情况下获取异常是否为 instanceof 的复杂方法

python - 如何在for循环python中跳过AttributeError并继续循环