To delete a directory with all contained files I chose the usage of shutil as common.
import shutil
from os.path import exists
if exists(path_dir):
shutil.rmtree(path_dir)
Unfortunatelly my solution does not work throwing the following error.
FileNotFoundError: [Errno 2] No such file or directory: '._image1.jpg'
A quick search showed that I'm not alone having this problem. Comparable, still unsolved question can be found here.
In my understanding rmtree
is equivalent to rm -Rf $DIR
which now seems not to be the case.
Any ideas appreciated.
p.s. for reconstruction purposes. Please create a symbolic link for example using ln -s /path/to/original /path/to/link
CodePudding user response:
From How to remove a directory including all its files in python?
# function that deletes all files and then folder
import glob, os
def del_folder(dir_name):
dir_path = os.getcwd() "\{}".format(dir_name)
try:
os.rmdir(dir_path) # remove the folder
except:
print("OSError") # couldn't remove the folder because we have files inside it
finally:
# now iterate through files in that folder and delete them one by one and delete the folder at the end
try:
for filepath in os.listdir(dir_path):
os.remove(dir_path "\{}".format(filepath))
os.rmdir(dir_path)
print("folder is deleted")
except:
print("folder is not there")
You can also just be able to use the ignore_errors
flag with shutil.rmtree().
shutil.rmtree('/folder_name', ignore_errors=True)
That should remove a directory with file contents.
CodePudding user response:
That is strange, I have no issues with shutil.rmtree() with or without symlink under the folder to be deleted, both in windows 10 and Ubuntu 20.04.2 LTS.
Anyhow try the following code. I tried it in windows 10 and Ubuntu.
from pathlib import Path
import shutil
def delete_dir(folder):
p = Path(folder)
if not p.exists():
print(f'The path {p} does not exists!')
return
# Attempt to delete the whole folder at once.
try:
shutil.rmtree(p)
except Exception as exception:
print(f'exception name: {exception.__class__.__name__}')
print(f'exception msg: {exception}')
# continue parsing the folder
else: # else if no issues on rmtree()
if not p.exists(): # verify
print(f'folder {p} was successfully deteted by shutil.rmtree!')
return
print(f'Parse the folder {folder} ...')
for f in p.glob('**/*'):
if f.is_file():
print(f'file: {f.name} will be deleted')
f.unlink() # delete file under folder
elif f.is_dir():
print(f'folder: {f.name} will be deleted')
try:
f.rmdir() # delete sub-folder
except NotADirectoryError:
f.unlink() # delete sub-folder symlink, linux
except Exception as exception:
print(f'exception name: {exception.__class__.__name__}')
print(f'exception msg: {exception}')
try:
p.rmdir() # time to delete an empty folder
except NotADirectoryError:
print(f'Deleting folder symlink {p}!')
p.unlink() # delete folder even if it is a symlink, linux
except Exception as exception:
print(f'exception name: {exception.__class__.__name__}')
print(f'exception msg: {exception}')
if not p.exists(): # verify
print(f'folder {p} was successfully deteted!')
# Start
folder_to_be_deleted = 'F:/sample/a/b' # delete folder b
delete_dir(folder_to_be_deleted)