Programing

파이썬에서 폴더를 재귀 적으로 삭제

lottogame 2020. 5. 26. 07:39
반응형

파이썬에서 폴더를 재귀 적으로 삭제


빈 디렉토리를 삭제하는 데 문제가 있습니다. 내 코드는 다음과 같습니다.

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'

어디에서 실수를합니까?


시도 shutil.rmtree:

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

기본 동작은 os.walk()루트에서 리프로 이동하는 것입니다. 설정 topdown=False에서 os.walk()루트 잎에서 걷는.


shutil 에서 rmtree를 사용해보십시오 . 파이썬 std 라이브러리에서


쇼에 약간 늦었지만 여기에 순수한 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/"))

절대 경로를 사용하고 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)

재귀 솔루션은 다음과 같습니다.

def clear_folder(dir):
    if os.path.exists(dir):
        for the_file in os.listdir(dir):
            file_path = os.path.join(dir, the_file)
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path)
                else:
                    clear_folder(file_path)
                    os.rmdir(file_path)
            except Exception as e:
                print(e)

여기 또 다른 순수 pathlib 솔루션은 있지만 없는 재귀 :

from pathlib import Path
from typing import Union

def del_empty_dirs(base: Union[Path, str]):
    base = Path(base)
    for p in sorted(base.glob('**/*'), reverse=True):
        if p.is_dir():
            p.chmod(0o666)
            p.rmdir()
        else:
            raise RuntimeError(f'{p.parent} is not empty!')
    base.rmdir()

참고URL : https://stackoverflow.com/questions/13118029/deleting-folders-in-python-recursively

반응형