programing

python에서 반복적으로 폴더 삭제

bestcode 2022. 11. 17. 21:12
반응형

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혼자만 삭제됩니다!하지만 폴더는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'

어디서 실수를 하는 걸까요?

시도:

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

다음은 순수 재귀 디렉토리 언링커입니다.

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/"))

의 기본 동작은 루트에서 리프까지 이동하는 것입니다.세트topdown=Falseos.walk()나뭇잎에서 뿌리까지 걸어다닌다.

해라rmtree()Python 표준 라이브러리에서 인

절대 경로를 사용하고 rmtree 함수만 가져오는 것이 좋습니다.from shutil import rmtree이것은 큰 패키지이기 때문에 위의 행은 필요한 기능만 Import합니다.

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)

명령어os.removedirs삭제할 경로를 하나만 찾는 경우, 다음과 같이 작업을 위한 도구입니다.

os.removedirs("a/b/c/empty1/empty2/empty3")

제거한다empty1/empty2/empty3단, a/b/c는 남겨둡니다(c에 다른 내용이 있는 것으로 가정합니다).

    removedirs(name)
        removedirs(name)
        
        Super-rmdir; remove a leaf directory and all empty intermediate
        ones.  Works like rmdir except that, if the leaf directory is
        successfully removed, directories corresponding to rightmost path
        segments will be pruned away until either the whole path is
        consumed or an error occurs.  Errors during this latter phase are
        ignored -- they generally mean that a directory was not empty.

다음pure-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()

여기 피톤적이고 재귀가 없는 해결책이 있습니다.

>>> for e in sorted(p.rglob('**/*'), key=lambda v: v.is_dir()):
...     try:
...         e.unlink()
...     except IsADirectoryError:
...         e.rmdir()

rglob()경로 내의 모든 파일과 디렉토리를 재귀적으로 제공합니다.p.그sorted()그것과 함께key인수는 결과가 파일별로 먼저 정렬되고 디렉토리가 마지막에 정렬되도록 주의합니다.이것에 의해, 우선 파일을 삭제해, 모든 디렉토리를 비울 수 있습니다.

try...except...부품은 저렴한 사용을 방지합니다.if진술들.

Linux 사용자의 경우 shell 명령어를 실행하기만 하면 됩니다.

import os
os.system("rm -r /home/user/folder1  /home/user/folder2  ...")

어떤 문제에 직면했을 경우,rm -r사용하다rm -rf, f는 디렉토리를 강제로 삭제합니다.

어디에rmremove를 나타냅니다.-r재귀적으로 그리고-rf재귀적으로 + 강제적으로.

주의: 디렉토리가 비어있든 비어있지 않든 상관없습니다.이 삭제됩니다.

언급URL : https://stackoverflow.com/questions/13118029/deleting-folders-in-python-recursively

반응형