【发布时间】: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