파일 또는 폴더를 삭제하려면 어떻게 합니까?
반응형
os.remove()
파일을 제거합니다.os.rmdir()
빈 디렉토리를 제거합니다.shutil.rmtree()
디렉토리와 모든 내용을 삭제합니다.
Path
Python 3.4+ pathlib
모듈의 객체는 다음 인스턴스 메서드도 노출합니다.
pathlib.Path.unlink()
파일이나 심볼릭 링크를 제거합니다.pathlib.Path.rmdir()
빈 디렉토리를 제거합니다.
파일을 삭제하는 Python 구문
import os
os.remove("/tmp/<file_name>.txt")
또는
import os
os.unlink("/tmp/<file_name>.txt")
또는
Python 버전용 pathlib 라이브러리 >= 3.4
file_to_rem = pathlib.Path("/tmp/<file_name>.txt")
file_to_rem.unlink()
Path.unlink(missing_ok=False)
파일 또는 심볼릭 링크를 제거하는 데 사용되는 링크 해제 방법입니다.
missing_ok가 false(기본값)이면 경로가 존재하지 않으면 FileNotFoundError가 발생합니다.
missing_ok가 true이면 FileNotFoundError 예외가 무시됩니다(POSIX rm -f 명령과 동일한 동작).
버전 3.8에서 변경: missing_ok 매개변수가 추가되었습니다.
모범 사례
- 먼저 파일이나 폴더가 있는지 확인하고 해당 파일만 삭제합니다. 이것은 두 가지 방법으로 달성할 수 있습니다
.os.path.isfile("/path/to/file")
비. 사용exception 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))
각 출력
삭제할 파일명 입력 : demo.txt 오류: demo.txt - 해당 파일이나 디렉토리가 없습니다. 삭제할 파일명 입력 : rrr.txt 오류: rrr.txt - 작업이 허용되지 않습니다. 삭제할 파일명 입력 : foo.txt
폴더를 삭제하는 Python 구문
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 에 대한 완전한 문서 )
반응형
'파이썬' 카테고리의 다른 글
[python] Python에서 수동으로 예외 발생(throw) (0) | 2022.08.22 |
---|---|
[python] Matplotlib으로 그린 그림의 크기를 어떻게 변경합니까? (0) | 2022.08.22 |
[python] __init__() 메서드로 Python super() 이해하기 [중복] (0) | 2022.08.22 |
[python] 함수 데코레이터를 만들고 함께 연결하려면 어떻게 해야 합니까? (0) | 2022.08.22 |
[python] **(이중 별표/별표) 및 *(별표/별표)는 매개변수에 대해 무엇을 합니까? (0) | 2022.08.22 |