파이썬에서 파일이나 폴더를 삭제하려면 어떻게합니까?
질문
파일이나 폴더는 어떻게 삭제합니까?
답변
os.remove () 파일을 제거합니다. os.rmdir () 빈 디렉토리를 제거합니다. shutil.rmtree () 디렉토리와 모든 내용을 삭제합니다.
Pathon 3.4+ PathLib 모듈에서 경로 객체는 이러한 인스턴스 메소드를 노출합니다.
pathlib.path.unlink () 파일 또는 기호 링크를 제거합니다. pathlib.path.rmdir () 빈 디렉토리를 제거합니다.
답변
파이썬 구문을 사용하여 파일을 삭제합니다
import os
os.remove("/tmp/<file_name>.txt")
또는
import os
os.unlink("/tmp/<file_name>.txt")
또는
Pathon 버전 용 PathLib 라이브러리> = 3.4.
file_to_rem = pathlib.Path("/tmp/<file_name>.txt")
file_to_rem.unlink()
path.unlink (menisk_ok = false)
파일 또는 기호 링크를 제거하는 데 사용되는 링크 방식입니다.
_oK가 false (기본값) 인 경우 경로가 존재하지 않으면 filenotfoundError가 발생합니다. _oK가 true이면 fileNotFoundError 예외가 무시됩니다 (posix rm -f 명령과 동일한 동작). 버전 3.8에서 변경됨 : menisk_ok 매개 변수가 추가되었습니다.
모범 사례
- First, check whether the file or folder exists or not then only delete that file. This can be achieved in two ways :
a.os.path.isfile("/path/to/file")
b. Useexception handling.
os.path.isfile의 예
#!/usr/bin/python
import os
myfile="/tmp/foo.txt"
## If file exists, delete it ##
if os.path.isfile(myfile):
os.remove(myfile)
else: ## Show an error ##
print("Error: %s file not found" % myfile)
예외 처리
#!/usr/bin/python
import os
## Get input ##
myfile= raw_input("Enter file name to delete: ")
## Try to delete the file ##
try:
os.remove(myfile)
except OSError as e: ## if failed, report it back to the user ##
print ("Error: %s - %s." % (e.filename, e.strerror))
각 출력
Enter file name to delete : demo.txt Error: demo.txt - No such file or directory. Enter file name to delete : rrr.txt Error: rrr.txt - Operation not permitted. Enter file name to delete : foo.txt
폴더를 삭제하는 파이썬 구문
shutil.rmtree()
shutil.rmtree ()의 예
#!/usr/bin/python
import os
import sys
import shutil
# Get directory name
mydir= raw_input("Enter directory name: ")
## Try to remove tree; if failed show an error using try...except on screen
try:
shutil.rmtree(mydir)
except OSError as e:
print ("Error: %s - %s." % (e.filename, e.strerror))
답변
사용
shutil.rmtree(path[, ignore_errors[, onerror]])
(Shutil의 전체 문서를 참조하십시오) 및 / 또는
os.remove
그리고
os.rmdir
(OS에 대한 문서를 완성하십시오.)
답변
다음은 os.remove 및 shutil.rmtree를 모두 사용하는 강력한 함수입니다.
def remove(path):
""" param <path> could either be relative or absolute. """
if os.path.isfile(path) or os.path.islink(path):
os.remove(path) # remove the file
elif os.path.isdir(path):
shutil.rmtree(path) # remove dir and all contains
else:
raise ValueError("file {} is not a file or dir.".format(path))
답변
내장 된 PathLib 모듈을 사용할 수 있습니다 (Python 3.4+ 필요 없지만 Pypi : PathLib, PathLib2에서 이전 버전의 백 포트가 있습니다).
파일을 제거하려면 해제 방법이 있습니다.
import pathlib
path = pathlib.Path(name_of_file)
path.unlink()
또는 빈 폴더를 제거하는 rmdir 방법 :
import pathlib
path = pathlib.Path(name_of_folder)
path.rmdir()
답변
파이썬에서 파일이나 폴더를 삭제하려면 어떻게합니까?
파이썬 3의 경우 파일과 디렉토리를 개별적으로 제거하려면 링크 링크 및 rmdir 경로 객체 메소드를 각각 사용하십시오.
from pathlib import Path
dir_path = Path.home() / 'directory'
file_path = dir_path / 'file'
file_path.unlink() # remove file
dir_path.rmdir() # remove directory
경로 객체가있는 상대 경로를 사용할 수도 있고 Path.cwd로 현재 작업 디렉토리를 확인할 수 있습니다.
Python 2에서 개별 파일 및 디렉토리를 제거하려면 아래에 표시된 섹션을 참조하십시오.
내용이있는 디렉토리를 제거하려면 shutil.rmtree를 사용하고 Python 2 및 3에서 사용할 수 있습니다.
from shutil import rmtree
rmtree(dir_path)
데모
Python 3.4의 새로운 기능은 경로 객체입니다.
사용법을 보여주기 위해 디렉토리와 파일을 만들려면 하나를 사용하십시오.우리는 경로의 부분을 사용하는 / to 경로의 부분을 사용하여 운영 체제와 Windows의 백 슬래시를 사용하는 문제 간 문제를 해결합니다 (\\처럼 백 슬래시를 두 배로 두어야하거나 r처럼 원시 문자열을 사용해야합니다)."foo \ bar") :
from pathlib import Path
# .home() is new in 3.5, otherwise use os.path.expanduser('~')
directory_path = Path.home() / 'directory'
directory_path.mkdir()
file_path = directory_path / 'file'
file_path.touch()
그리고 지금:
>>> file_path.is_file()
True
이제 삭제하겠습니다.첫 번째 파일 :
>>> file_path.unlink() # remove file
>>> file_path.is_file()
False
>>> file_path.exists()
False
우리는 글로 딩을 사용하여 여러 파일을 제거 할 수 있습니다. 먼저 몇 가지 파일을 만들려고합니다.
>>> (directory_path / 'foo.my').touch()
>>> (directory_path / 'bar.my').touch()
그런 다음 GLOB 패턴을 반복합니다.
>>> for each_file_path in directory_path.glob('*.my'):
... print(f'removing {each_file_path}')
... each_file_path.unlink()
...
removing ~/directory/foo.my
removing ~/directory/bar.my
이제 디렉토리 제거를 시연합니다.
>>> directory_path.rmdir() # remove directory
>>> directory_path.is_dir()
False
>>> directory_path.exists()
False
디렉토리와 모든 것을 제거하려는 경우 어떻게해야합니까? 이 유스 케이스의 경우 shutil.rmtree를 사용하십시오
디렉토리와 파일을 다시 만들어 보겠습니다.
file_path.parent.mkdir()
file_path.touch()
RMDIR이 비어 있지 않으면 실패합니다. 이는 RMTree가 매우 편리합니다.
>>> directory_path.rmdir()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "~/anaconda3/lib/python3.6/pathlib.py", line 1270, in rmdir
self._accessor.rmdir(self)
File "~/anaconda3/lib/python3.6/pathlib.py", line 387, in wrapped
return strfunc(str(pathobj), *args)
OSError: [Errno 39] Directory not empty: '/home/username/directory'
이제 RMTree를 가져 와서 디렉토리를 함수로 전달하십시오.
from shutil import rmtree
rmtree(directory_path) # remove everything
그리고 우리는 모든 것을 제거한 것을 볼 수 있습니다 :
>>> directory_path.exists()
False
파이썬 2.
파이썬 2에있는 경우 PATHLIB2라는 PATHLIB 모듈의 백 포트가 있습니다. 이는 PIP와 함께 설치할 수 있습니다.
$ pip install pathlib2
그리고 나서 라이브러리를 PathLib에 별칭 할 수 있습니다
import pathlib2 as pathlib
또는 경로 객체를 직접 가져 오는 경우 (여기에서 설명한대로) :
from pathlib2 import Path
그게 너무 많으면 os.remove 또는 os.unlink로 파일을 제거 할 수 있습니다.
from os import unlink, remove
from os.path import join, expanduser
remove(join(expanduser('~'), 'directory/file'))
또는
unlink(join(expanduser('~'), 'directory/file'))
그리고 os.rmdir를 사용하여 디렉토리를 제거 할 수 있습니다.
from os import rmdir
rmdir(join(expanduser('~'), 'directory'))
os.removedirs가 있음에 유의하십시오. 빈 디렉토리 만 재귀 적으로 제거하지만 사용 사례에 맞게 사용할 수 있습니다.
출처:https://stackoverflow.com/questions/6996603/how-do-i-delete-a-file-or-folder-in-python
최근댓글