[python] 비어 있지 않은 폴더는 어떻게 제거 / 삭제합니까?

비어 있지 않은 폴더를 삭제하려고하면 ‘액세스가 거부되었습니다’오류가 발생합니다. 시도 할 때 다음 명령을 사용했습니다 os.remove("/folder_name")..

비어 있지 않은 폴더 / 디렉토리를 제거 / 삭제하는 가장 효과적인 방법은 무엇입니까?



답변

import shutil

shutil.rmtree('/folder_name')

표준 라이브러리 참조 : shutil.rmtree .

의도적으로 rmtree읽기 전용 파일이 포함 된 폴더 트리 에서는 실패합니다. 읽기 전용 파일이 포함되어 있는지 여부에 관계없이 폴더를 삭제하려면 다음을 사용하십시오.

shutil.rmtree('/folder_name', ignore_errors=True)


답변

에서 파이썬 문서os.walk():

# Delete everything reachable from the directory named in 'top',
# assuming there are no symbolic links.
# CAUTION:  This is dangerous!  For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
    for name in files:
        os.remove(os.path.join(root, name))
    for name in dirs:
        os.rmdir(os.path.join(root, name))


답변

import shutil
shutil.rmtree(dest, ignore_errors=True)


답변

파이썬 3.4에서 사용할 수 있습니다 :

import pathlib

def delete_folder(pth) :
    for sub in pth.iterdir() :
        if sub.is_dir() :
            delete_folder(sub)
        else :
            sub.unlink()
    pth.rmdir() # if you just want to delete dir content, remove this line

인스턴스 pth는 어디에 있습니까 pathlib.Path? 좋지만 가장 빠르지는 않을 수 있습니다.


답변

에서 docs.python.org :

이 예는 일부 파일에 읽기 전용 비트가 설정된 Windows에서 디렉토리 트리를 제거하는 방법을 보여줍니다. 읽기 전용 비트를 지우고 제거를 다시 시도하기 위해 onerror 콜백을 사용합니다. 후속 실패는 전파됩니다.

import os, stat
import shutil

def remove_readonly(func, path, _):
    "Clear the readonly bit and reattempt the removal"
    os.chmod(path, stat.S_IWRITE)
    func(path)

shutil.rmtree(directory, onerror=remove_readonly)

답변

import os
import stat
import shutil

def errorRemoveReadonly(func, path, exc):
    excvalue = exc[1]
    if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES:
        # change the file to be readable,writable,executable: 0777
        os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
        # retry
        func(path)
    else:
        # raiseenter code here

shutil.rmtree(path, ignore_errors=False, onerror=errorRemoveReadonly) 

ignore_errors가 설정되면 오류가 무시됩니다. 그렇지 않으면, onerror가 설정되면 인수 (func, path, exc_info)로 오류를 처리하기 위해 호출됩니다. 여기서 func는 os.listdir, os.remove 또는 os.rmdir입니다. path는 실패한 함수에 대한 인수입니다. exc_info는 sys.exc_info ()에 의해 반환 된 튜플입니다. ignore_errors가 false이고 onerror가 None이면 예외가 발생합니다.


답변

kkubasik의 답변을 바탕으로 폴더를 제거하기 전에 폴더가 있는지 확인하십시오.

import shutil
def remove_folder(path):
    # check if folder exists
    if os.path.exists(path):
         # remove if exists
         shutil.rmtree(path)
    else:
         # throw your exception to handle this special scenario
         raise XXError("your exception")
remove_folder("/folder_name")