파이썬에서 폴더의 내용을 삭제하는 방법?
파이썬에서 로컬 폴더의 내용을 어떻게 삭제합니까?
현재 프로젝트는 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)
독 스트링 : 디렉토리 트리를 재귀 적으로 삭제합니다.
경우
ignore_errors
설정, 오류는 무시됩니다; 그렇지 않으면,onerror
설정, 인수를 사용하여 오류 처리하기 위해 호출 이다 , 또는를 ; path는 실패한 함수에 대한 인수입니다. 에서 반환 한 튜플 입니다. 경우 거짓과 입니다 , 예외가 발생합니다.(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)
다른 많은 답변과 마찬가지로 파일 / 디렉토리를 제거 할 수 있도록 권한을 조정하지 않습니다.
메모 : 누군가 내 대답에 투표를 한 경우 여기에 설명 할 것이 있습니다.
- 누구나 짧은 'n'간단한 답변을 좋아합니다. 그러나 때로는 현실이 그렇게 간단하지 않습니다.
- 내 대답으로 돌아 가기
shutil.rmtree()
디렉토리 트리를 삭제하는 데 사용될 수 있다는 것을 알고 있습니다. 내 프로젝트에서 여러 번 사용했습니다. 그러나 디렉토리 자체도에 의해 삭제됨을 알아야합니다shutil.rmtree()
. 일부 사용자에게는 허용 될 수 있지만 폴더의 내용 을 삭제하는 데에는 부작용이없는 올바른 답변이 아닙니다 . - 부작용의 예를 보여 드리겠습니다. 내용이 많은 사용자 정의 된 소유자 및 모드 비트 가있는 디렉토리가 있다고 가정하십시오 . 그런 다음로 삭제
shutil.rmtree()
하고 다시 빌드하십시오os.mkdir()
. 그리고 기본 (상속 된) 소유자 및 모드 비트 가있는 빈 디렉토리가 나타납니다 . 컨텐츠 및 디렉토리를 삭제할 권한이있을 수 있지만 디렉토리에서 원래 소유자 및 모드 비트를 다시 설정하지 못할 수 있습니다 (예 : 수퍼 유저가 아님). - 마지막으로 인내심을 갖고 코드를 읽으십시오 . 길고 못 생겼지 만 (시각적으로) 신뢰할 수 있고 효율적 (사용 중)으로 입증되었습니다.
길고 추악하지만 신뢰할 수 있고 효율적인 솔루션입니다.
다른 응답자가 해결하지 않은 몇 가지 문제를 해결합니다.
- 그것은 심볼릭 링크를 호출하지 않는 것을 포함하여 심볼릭 링크를 올바르게 처리
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
# 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)) )
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()
파일을 디렉토리와 구별하지 않으므로 링크를 해제하려고 시도하는 데 어려움이 있습니다. hereos.walk()
디렉토리를 재귀 적으로 제거하는 데 사용하는 좋은 예가 있으며 , 환경에 맞게 디렉토리 를 조정하는 방법에 대한 힌트를 제공합니다.
이런 식으로 문제를 해결하는 데 사용했습니다.
import shutil
import os
shutil.rmtree(dirpath)
os.mkdir(dirpath)
나는 그것이 오래된 실이라고 생각했지만 파이썬의 공식 사이트에서 흥미로운 것을 발견했습니다. 디렉토리의 모든 내용을 제거하기위한 또 다른 아이디어를 공유하기위한 것입니다. 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/*'))
나는 아무도이 일을하는 것을 언급 한 것에 놀랐 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)
* nix 시스템을 사용하는 경우 시스템 명령을 활용하지 않겠습니까?
import os
path = 'folder/to/clean'
os.system('rm -rf %s/*' % path)
매우 직관적 인 방법 :
import shutil, os
def remove_folder_contents(path):
shutil.rmtree(path)
os.makedirs(path)
remove_folder_contents('/path/to/folder')
다음 사이 rmtree
makedirs
에 추가 하여 문제를 해결했습니다 time.sleep()
.
if os.path.isdir(folder_location):
shutil.rmtree(folder_location)
time.sleep(.5)
os.makedirs(folder_location, 0o777)
간단히하세요. 하위 디렉토리뿐만 아니라 디렉토리 내의 모든 파일이 삭제됩니다. 폴더 / 디렉토리에 해를 끼치 지 않습니다. 오류없이 우분투에서 잘 작동합니다.
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))
제한된 특정 상황에 대한 답 : 하위 폴더 트리를 유지하면서 파일을 삭제한다고 가정하면 순환 알고리즘을 사용할 수 있습니다.
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
files = os.listdir(yourFilePath)
for f in files:
os.remove(yourFilePath + f)
이것은 OS 모듈을 사용하여 나열하고 제거하는 트릭을 수행해야합니다!
import os
DIR = os.list('Folder')
for i in range(len(DIR)):
os.remove('Folder'+chr(92)+i)
나를 위해 일한, 어떤 문제라도 알려주십시오!
참고 URL : https://stackoverflow.com/questions/185936/how-to-delete-the-contents-of-a-folder-in-python
'Programing' 카테고리의 다른 글
Java 보안 : 잘못된 키 크기 또는 기본 매개 변수? (0) | 2020.02.23 |
---|---|
div를 가리킬 때 다른 요소에 영향을 미치는 방법 (0) | 2020.02.23 |
테이블의 전체 행을 링크로 클릭 가능하게 만드는 방법은 무엇입니까? (0) | 2020.02.23 |
표준 C ++ / C ++ 11 / C를 사용하여 파일이 존재하는지 확인하는 가장 빠른 방법은 무엇입니까? (0) | 2020.02.23 |
vi / Vim에서 여러 줄을 선택할 때 텍스트를 어떻게 삽입합니까? (0) | 2020.02.23 |