Удаление папок в python рекурсивно



у меня есть проблема в удалении пустых каталогов. У меня есть такой код:



for dirpath, dirnames, filenames in os.walk(dir_to_search):
//other codes

try:
os.rmdir(dirpath)
except OSError as ex:
print(ex)


аргумент dir_to_search это где я передаю каталог, где работа должна быть вниз. Этот каталог выглядит так:



test/20/...
test/22/...
test/25/...
test/26/...


обратите внимание, что все вышеуказанные папки пусты. Когда я запускаю этот скрипт папки 20, удаляется! Но папки 25 и 26 не удаляются, даже если они пустые папки.



Edit:



исключение, которое я получаю это:



[Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test'
[Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test/2012'
[Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test/2012/10'
[Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test/2012/10/29'
[Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test/2012/10/29/tmp'
[Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test/2012/10/28'
[Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test/2012/10/28/tmp'
[Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test/2012/10/26'
[Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test/2012/10/25'
[Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test/2012/10/27'
[Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test/2012/10/27/tmp'


где я делаю ошибку.



спасибо заранее.

614   6  

6 ответов:

попробовать shutil.rmtree:

import shutil
shutil.rmtree('/path/to/your/dir/')

по умолчанию os.walk() Это ходить от корня к листу. Набор topdown=False in os.walk() ходить от листа к корню.

попробуйте rmtree в shutil. в библиотеке python std

лучше использовать абсолютный путь и импортировать только функцию rmtree from shutil import rmtree поскольку это большой пакет, приведенная выше строка будет импортировать только необходимую функцию.

from shutil import rmtree
rmtree('directory-absolute-path')

немного поздно для шоу, но вот мой чистый Pathlib рекурсивный каталог unlinker

def rmdir(dir):
    dir = Path(dir)
    for item in dir.iterdir():
        if item.is_dir():
            rmdir(item)
        else:
            item.unlink()
    dir.rmdir()

rmdir(pathlib.Path("dir/"))

команда (данная Томеком)не могу удалить файл, если это только для чтения. поэтому можно использовать -

import os, sys
from stat import *

def del_evenReadonly(action, name, exc):
    os.chmod(name, stat.S_IWRITE)
    os.remove(name)

if  os.path.exists("test/qt_env"):
    shutil.rmtree('test/qt_env',onerror=del_evenReadonly)

Comments

    Ничего не найдено.