문제

Python에서 로컬 폴더의 내용을 삭제하려면 어떻게해야합니까?

현재 프로젝트는 Windows를위한 것이지만 *nix도보고 싶습니다.

도움이 되었습니까?

해결책

파일 만 삭제하고 사용하도록 업데이트되었습니다 os.path.join() 주석에서 제안 된 방법. 하위 디렉토리를 제거하려면 타협하지 않으려면 elif 성명.

import os, shutil
folder = '/path/to/folder'
for the_file in os.listdir(folder):
    file_path = os.path.join(folder, the_file)
    try:
        if os.path.isfile(file_path):
            os.unlink(file_path)
        #elif os.path.isdir(file_path): shutil.rmtree(file_path)
    except Exception as e:
        print(e)

다른 팁

Shutil 모듈을 사용해보십시오

import shutil
shutil.rmtree('/path/to/folder')

설명: shutil.rmtree(path, ignore_errors=False, onerror=None)

docstring : 디렉토리 트리를 재귀 적으로 삭제합니다.

만약에 ignore_errors 설정되면 오류가 무시됩니다. 그렇지 않으면 if onerror 설정되었고 인수로 오류를 처리하도록 호출됩니다. (func, path, exc_info) 어디 func ~이다 os.listdir, os.remove, 또는 os.rmdir; 경로는 그 기능이 실패하게 한 주장이다. 그리고 exc_info 튜플이 반환됩니다 sys.exc_info(). 만약에 ignore_errors 거짓이고 onerror ~이다 None, 예외가 제기됩니다.

중요 사항: 알고 있어야합니다 shutil.rmtree() 대상 폴더의 내용 만 삭제하지 않습니다. 폴더 자체도 삭제합니다.

당신은 단순히 이것을 할 수 있습니다 :

import os
import glob

files = glob.glob('/YOUR/PATH/*')
for f in files:
    os.remove(f)

물론 디렉토리에서 모든 텍스트 파일을 제거하려면/you/path/* .txt와 같은 경로에서 다른 필터를 사용할 수 있습니다.

Mhawke의 답변을 확장하면 이것이 제가 구현 한 것입니다. 폴더 자체는 폴더 자체의 모든 내용을 제거합니다. 파일, 폴더 및 기호 링크로 Linux에서 테스트 한 것은 Windows에서도 작동해야합니다.

import os
import shutil

for root, dirs, files in os.walk('/path/to/folder'):
    for f in files:
        os.unlink(os.path.join(root, f))
    for d in dirs:
        shutil.rmtree(os.path.join(root, d))

사용 rmtree 폴더를 재현하는 것은 작동 할 수 있지만 네트워크 드라이브에서 폴더를 삭제하고 즉시 재현 할 때 오류가 발생했습니다.

Walk를 사용하는 제안 된 솔루션은 사용하는대로 작동하지 않습니다. rmtree 폴더를 제거한 다음 사용하려고 시도 할 수 있습니다 os.unlink 이전에 해당 폴더에 있던 파일에 이로 인해 오류가 발생합니다.

게시 된 glob 솔루션은 또한 비어 있지 않은 폴더를 삭제하여 오류를 일으 킵니다.

나는 당신이 사용하는 것이 좋습니다 :

folder_path = '/path/to/folder'
for file_object in os.listdir(folder_path):
    file_object_path = os.path.join(folder_path, file_object)
    if os.path.isfile(file_object_path):
        os.unlink(file_object_path)
    else:
        shutil.rmtree(file_object_path)

이것은 지금까지 유일한 대답입니다.

  • 모든 기호 링크를 제거합니다
    • 죽은 링크
    • 디렉토리 링크
    • 파일 링크
  • 하위 디렉터를 제거합니다
  • 부모 디렉토리를 제거하지 않습니다

암호:

for filename in os.listdir(dirpath):
    filepath = os.path.join(dirpath, filename)
    try:
        shutil.rmtree(filepath)
    except OSError:
        os.remove(filepath)

다른 많은 답변처럼 파일/디렉토리를 제거하기 위해 권한을 조정하려고 시도하지 않습니다.

OneLiner로 :

import os

# Python 2.7
map( os.unlink, (os.path.join( mydir,f) for f in os.listdir(mydir)) )

# Python 3+
list( map( os.unlink, (os.path.join( mydir,f) for f in os.listdir(mydir)) ) )

파일 및 디렉토리를 설명하는보다 강력한 솔루션은 (2.7)입니다.

def rm(f):
    if os.path.isdir(f): return os.rmdir(f)
    if os.path.isfile(f): return os.unlink(f)
    raise TypeError, 'must be either file or directory'

map( rm, (os.path.join( mydir,f) for f in os.listdir(mydir)) )

참고 : 누군가가 내 대답에 투표 한 경우 여기에 설명 할 것이 있습니다.

  1. 누구나 짧은 'n'간단한 답변을 좋아합니다. 그러나 때로는 현실이 그렇게 간단하지 않습니다.
  2. 내 대답으로 돌아갑니다. 알아요 shutil.rmtree() 디렉토리 트리를 삭제하는 데 사용될 수 있습니다. 나는 내 프로젝트에서 여러 번 사용했습니다. 그러나 당신은 그것을 깨달아야합니다 디렉토리 자체도 삭제됩니다 shutil.rmtree(). 이것은 일부에게는 허용 될 수 있지만 유효한 답변은 아닙니다. 폴더의 내용 삭제 (부작용 없음).
  3. 부작용의 예를 보여 드리겠습니다. 디렉토리가 있다고 가정 해 봅시다 사용자 정의 많은 내용이있는 소유자 및 모드 비트. 그런 다음 삭제합니다 shutil.rmtree() 그리고 그것을 재건하십시오 os.mkdir(). 그리고 당신은 빈 디렉토리를 얻을 수 있습니다 기본 (상속) 소유자 및 모드 비트 대신. 내용과 디렉토리를 삭제할 권한이 있지만 디렉토리에서 원래 소유자와 모드 비트를 다시 설정하지 못할 수도 있습니다 (예 : 슈퍼 서서가 아님).
  4. 드디어, 인내하고 코드를 읽으십시오. 길고 못 생겼지 만 (눈에 띄지 않지만) 신뢰할 수 있고 효율적으로 입증되었습니다 (사용 중).

다음은 길고 추악하지만 신뢰할 수 있고 효율적인 솔루션입니다.

다른 답변자가 해결하지 못하는 몇 가지 문제를 해결합니다.

  • 호출을 포함한 기호 링크를 올바르게 처리합니다 shutil.rmtree() 상징적 인 링크에 ( os.path.isdir() 디렉토리에 연결되는지 테스트하십시오. 의 결과조차도 os.walk() 기호 연결된 디렉토리도 포함).
  • 읽기 전용 파일을 잘 처리합니다.

코드는 다음과 같습니다 (유일한 유용한 기능은 clear_dir()):

import os
import stat
import shutil


# http://stackoverflow.com/questions/1889597/deleting-directory-in-python
def _remove_readonly(fn, path_, excinfo):
    # Handle read-only files and directories
    if fn is os.rmdir:
        os.chmod(path_, stat.S_IWRITE)
        os.rmdir(path_)
    elif fn is os.remove:
        os.lchmod(path_, stat.S_IWRITE)
        os.remove(path_)


def force_remove_file_or_symlink(path_):
    try:
        os.remove(path_)
    except OSError:
        os.lchmod(path_, stat.S_IWRITE)
        os.remove(path_)


# Code from shutil.rmtree()
def is_regular_dir(path_):
    try:
        mode = os.lstat(path_).st_mode
    except os.error:
        mode = 0
    return stat.S_ISDIR(mode)


def clear_dir(path_):
    if is_regular_dir(path_):
        # Given path is a directory, clear its content
        for name in os.listdir(path_):
            fullpath = os.path.join(path_, name)
            if is_regular_dir(fullpath):
                shutil.rmtree(fullpath, onerror=_remove_readonly)
            else:
                force_remove_file_or_symlink(fullpath)
    else:
        # Given path is a file or a symlink.
        # Raise an exception here to avoid accidentally clearing the content
        # of a symbolic linked directory.
        raise OSError("Cannot call clear_dir() on a symbolic link")
import os
import shutil

# Gather directory contents
contents = [os.path.join(target_dir, i) for i in os.listdir(target_dir)]

# Iterate and remove each item in the appropriate manner
[os.remove(i) if os.path.isfile(i) or os.path.islink(i) else shutil.rmtree(i) for i in contents]

이전 의견은 Python 3.5+에서 OS.Scandir를 사용하는 것도 언급합니다. 예를 들어:

import os
import shutil

with os.scandir(target_dir) as entries:
    for entry in entries:
        if entry.is_file() or entry.is_symlink():
            os.remove(entry.path)
        elif entry.is_dir():
            shutil.rmtree(entry.path)

당신은 사용하는 것이 더 나을 수 있습니다 os.walk() 이것을 위해.

os.listdir() 파일을 디렉토리와 구별하지 않으며이를 링크하지 않도록 빠르게 문제가 발생합니다. 사용의 좋은 예가 있습니다 os.walk() 디렉토리를 재귀 적으로 제거합니다 여기, 그리고 당신의 상황에 적응하는 방법에 대한 힌트.

이런 식으로 문제를 해결했습니다.

import shutil
import os

shutil.rmtree(dirpath)
os.mkdir(dirpath)

나는 그것이 오래된 실이지만, 나는 Python의 공식 사이트에서 흥미로운 것을 발견했습니다. 디렉토리에서 모든 내용을 제거하기위한 다른 아이디어를 공유하기 만하면됩니다. shutil.rmtree ()를 사용할 때 허가 문제가 있고 디렉토리를 제거하고 다시 만들고 싶지 않기 때문입니다. 주소 원본은입니다 http://docs.python.org/2/library/os.html#os.walk. 그것이 누군가를 도울 수 있기를 바랍니다.

def emptydir(top):
    if(top == '/' or top == "\\"): return
    else:
        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 sh
sh.rm(sh.glob('/path/to/folder/*'))

*nix 시스템을 사용하는 경우 시스템 명령을 활용하지 않겠습니까?

import os
path = 'folder/to/clean'
os.system('rm -rf %s/*' % path)

나는 아무도 굉장한 것을 언급하지 않았다는 것에 놀랐다 pathlib 이 일을하기 위해.

디렉토리에서 파일 만 제거하려면 OnEliner가 될 수 있습니다.

from pathlib import Path

[f.unlink() for f in Path("/path/to/folder").glob("*") if f.is_file()] 

디렉토리를 재귀 적으로 제거하려면 다음과 같은 글을 쓸 수 있습니다.

from pathlib import Path
from shutil import rmtree

for path in Path("/path/to/folder").glob("**/*"):
    if path.is_file():
        path.unlink()
    elif path.is_dir():
        rmtree(path)

나는 문제를 해결했다 rmtree makedirs 추가하여 time.sleep() 사이:

if os.path.isdir(folder_location):
    shutil.rmtree(folder_location)

time.sleep(.5)

os.makedirs(folder_location, 0o777)

제한된 특정 상황에 대한 답변 : Subfolders 트리를 관리하는 동안 파일을 삭제하려고한다고 가정하면 재귀 알고리즘을 사용할 수 있습니다.

import os

def recursively_remove_files(f):
    if os.path.isfile(f):
        os.unlink(f)
    elif os.path.isdir(f):
        map(recursively_remove_files, [os.path.join(f,fi) for fi in os.listdir(f)])

recursively_remove_files(my_directory)

어쩌면 약간 주제를 벗어나지 만 많은 사람들이 유용하다고 생각합니다.

가정합니다 temp_dir 삭제하려면 단일 라인 명령을 사용합니다 os 다음과 같습니다.

_ = [os.remove(os.path.join(save_dir,i)) for i in os.listdir(temp_dir)]

참고 : 파일을 삭제하기위한 1 라이너 일뿐입니다.

도움이 되었기를 바랍니다. 감사.

방법을 사용하여 디렉토리 자체가 아닌 디렉토리의 내용을 제거하십시오.

import os
import shutil

def remove_contents(path):
    for c in os.listdir(path):
        full_path = os.path.join(path, c)
        if os.path.isfile(full_path):
            os.remove(full_path)
        else:
            shutil.rmtree(full_path)

단순히 이것을 수행하십시오. 이렇게하면 디렉토리 내부의 모든 파일과 하위 디렉터도 삭제됩니다. 폴더/디렉토리에 해를 끼치 지 않고 오류없이 우분투에서 잘 작동합니다.

import os
mypath = "my_folder" #Enter your path here
for root, dirs, files in os.walk(mypath):
    for file in files:
        os.remove(os.path.join(root, file))

이것은 OS 모듈을 사용하여 트릭을 수행하여 나와 제거해야합니다!

import os
DIR = os.list('Folder')
for i in range(len(DIR)):
    os.remove('Folder'+chr(92)+i)

나를 위해 일했는데 모든 문제가 알려주세요!

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top