【问题标题】:why python is dropping errors after execution is being completed为什么python在执行完成后会丢弃错误
【发布时间】:2020-06-24 21:41:49
【问题描述】:

我编写渗透到文件夹内部的程序并检查文件夹是否有包含文件的子文件夹是否有包含程序内部文件的文件夹再次渗透到它并删除所有创建的文件以使文件夹为空并且准备好删除它,但是在执行程序后,当目录中有许多文件夹和文件时,我收到以下错误

PermissionError: [WinError 5] Access is denied: 'FileLocation\\Folder'

如果该目录中的目录名称有两个或多个单词,它们之间带有空格分隔符,则程序运行良好,但会出现以下错误

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'FileLocation\\firstName secondName'

我用唯一的 os 模块编写的代码就是下面的代码

import os

# parent folder
New = "C:\\Users\\HP\\Desktop\\New"

# check if the path exists
if os.path.exists(New):
# looping over all files and directories inside the parent folder
for files in os.listdir(New):
    # check if there is directories
    if os.path.isdir(New + '\\' + files):
        # check if the directories are empty and get ready to remove it
        if len(os.listdir(New + '\\' + files)) <= 0:
            os.rmdir(New + '\\' + files)
        # when directories are not empty
        else:
            # search for file inside the nested directories
            for sub_files in os.listdir(New + '\\' + files):
                # remove all the files inside the nested directories
                os.remove(New + '\\' + files + "\\" + sub_files)
        # remove directories after removing files inside it
        os.removedirs(New + '\\' + files)
    # check if there is files
    if os.path.isfile(New + '\\' + files):
        # removing the files inside the parent folder
        os.remove(New + '\\' + files)
# removing the entire folder after deleting all files and folders inside it
os.rmdir(New)
else:
    print('Folder doesn\'t exist')

当我编写程序时,如下代码运行良好,没有任何逻辑或运行时错误,其代码如下与 shutil 和 os 模块

import shutil
import os

# parent folder
New = "C:\\Users\\HP\\Desktop\\New"
if os.path.exists(New):
     shutil.rmtree(New)
else:
    print('Folder doesn\'t exist')

所以我想知道是否有任何关于 python 错误的进一步配置或我的代码中的任何错误要修复或任何方式在运行时不会出现错误,这将更好(删除不为空的目录)谢谢

【问题讨论】:

  • 我只是想用第一种方法删除嵌套目录,但有时会出错,我不知道为什么是我的错误或配置不佳

标签: python file-handling shutil python-os


【解决方案1】:

我相信是这部分:

    if len(os.listdir(New + '\\' + files)) <= 0:
        os.rmdir(New + '\\' + files)
    # when directories are not empty
    else:
        # search for file inside the nested directories
        for sub_files in os.listdir(New + '\\' + files):
            # remove all the files inside the nested directories
            os.remove(New + '\\' + files + "\\" + sub_files)

你有if len(os.listdir(New + '\\' + files)) &lt;= 0:,这意味着如果文件夹是空的。
您还有else:,用于非空文件夹。
但是,如果在那个文件夹中,还有另一个不是空的文件夹,
你不能在那个文件夹上调用os.remove(New + '\\' + files + "\\" + sub_files)
所以它会抛出一个PermissionError: [WinError 5] Access is denied错误。

【讨论】:

    【解决方案2】:

    在 Pychrarm 或 CMD 上单击右键以运行脚本并选择以​​系统管理员身份运行

    【讨论】:

    • 我总是以管理员身份运行编辑器,我想这不是问题
    猜你喜欢
    • 1970-01-01
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    • 2011-07-03
    • 1970-01-01
    • 1970-01-01
    • 2014-06-05
    • 1970-01-01
    相关资源
    最近更新 更多