폴더의 내용을 삭제하는 방법? 폴더의 내용을 어떻게 삭제합니까? 현재 프로젝트는

파이썬에서 로컬 폴더의 내용을 어떻게 삭제합니까?

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



답변

import os, shutil
folder = '/path/to/folder'
for filename in os.listdir(folder):
    file_path = os.path.join(folder, filename)
    try:
        if os.path.isfile(file_path) or os.path.islink(file_path):
            os.unlink(file_path)
        elif os.path.isdir(file_path):
            shutil.rmtree(file_path)
    except Exception as e:
        print('Failed to delete %s. Reason: %s' % (file_path, e))


답변

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

import os
import glob

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

디렉토리의 모든 텍스트 파일을 제거하기 위해 경로에 다른 필터를 사용할 수도 있습니다 (예 : /YOU/PATH/*.txt).


답변

다음을 사용하여 폴더 자체와 모든 내용을 삭제할 수 있습니다 shutil.rmtree.

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

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

전체 디렉토리 트리를 삭제하십시오. 경로 는 디렉토리를 가리켜 야합니다 (디렉토리에 대한 심볼릭 링크는 아님). 경우 ignore_errors는 사실, 실패 제거로 인한 오류는 무시됩니다; false이거나 생략 된 경우, 이러한 오류는 onerror에 의해 지정된 핸들러를 호출하여 처리 되거나 생략되면 예외를 발생시킵니다.


답변

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) or os.path.islink(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)

다른 많은 답변과 마찬가지로 파일 / 디렉토리를 제거 할 수 있도록 권한을 조정하지 않습니다.


답변

원 라이너로서 :

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