빈 디렉토리를 삭제하는 데 문제가 있습니다. 내 코드는 다음과 같습니다.
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혼자 삭제됩니다! 그러나 폴더 25와는 26비어 폴더에도 불구하고, 삭제되지 않습니다.
편집하다:
내가 얻는 예외는 다음과 같습니다.
[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'어디에서 실수를합니까?
답변
답변
기본 동작은 os.walk()루트에서 리프로 이동하는 것입니다. 설정 topdown=False에서 os.walk()루트 잎에서 걷는.
답변
내 순수한 pathlib재귀 디렉토리 unlinker는 다음과 같습니다 .
from pathlib import Path
def rmdir(directory):
    directory = Path(directory)
    for item in directory.iterdir():
        if item.is_dir():
            rmdir(item)
        else:
            item.unlink()
    directory.rmdir()
rmdir(Path("dir/"))답변
시도 rmtree()에서 shutil파이썬 표준 라이브러리에서
답변
절대 경로를 사용하고 rmtree 함수
 from shutil import rmtree
만 가져 오는 것이 좋습니다. 위의 행은 필요한 함수 만 가져옵니다.
from shutil import rmtree
rmtree('directory-absolute-path')답변
다음에 마이크로 파이썬 솔루션을 검색하는 사람은 os (listdir, remove, rmdir)를 기반으로합니다. 완전하지 않거나 (특히 오류 처리에서) 화려하지는 않지만 대부분의 상황에서 작동합니다.
def deltree(target):
    print("deltree", target)
    for d in os.listdir(target):
        try:
            deltree(target + '/' + d)
        except OSError:
            os.remove(target + '/' + d)
    os.rmdir(target)답변
Tomek에서 제공 한 명령 은 파일이 읽기 전용 인 경우 파일을 삭제할 수 없습니다 . 따라서 사용할 수 있습니다-
import os, sys
import stat
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)