티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

How do I remove/delete a folder that is not empty?

비어 있지 않은 폴더를 제거/삭제하려면 어떻게 해야 합니까?

 문제 내용 

I am getting an 'access is denied' error when I attempt to delete a folder that is not empty. I used the following command in my attempt: os.remove("/folder_name").

비어 있지 않은 폴더를 삭제하려고 하면 '액세스 거부' 오류가 표시됩니다. 저는 os.remove("/folder_name") 명령어를 사용했습니다.

 

What is the most effective way of removing/deleting a folder/directory that is not empty?

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

 

 

 

 높은 점수를 받은 Solution 

import shutil

shutil.rmtree('/folder_name')

Standard Library Reference: shutil.rmtree.

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

 

By design, rmtree fails on folder trees containing read-only files. If you want the folder to be deleted regardless of whether it contains read-only files, then use

설계상 rmtree는 읽기 전용 파일을 포함하는 폴더 트리에서 실패합니다. 읽기 전용 파일을 포함하는지 여부에 관계없이 폴더를 삭제하려면
shutil.rmtree('/folder_name', ignore_errors=True)

 

 

 가장 최근 달린 Solution 

Recursion-based, pure pathlib solution:

재귀 기반의 순수한 pathlib 솔루션:
from pathlib import Path

def remove_path(path: Path):
    if path.is_file() or path.is_symlink():
        path.unlink()
        return
    for p in path.iterdir():
        remove_path(p)
    path.rmdir()

 

Supports Windows and symbolic links

윈도우즈 및 심볼릭 링크 지원

 

 

 

출처 : https://stackoverflow.com/questions/303200/how-do-i-remove-delete-a-folder-that-is-not-empty

반응형
댓글
공지사항
최근에 올라온 글