Notice
Recent Posts
Recent Comments
Link
SeouliteLab
[Python/파이썬] 파일, 폴더 삭제 본문
파이썬에서는 파일과 폴더를 삭제하는 다양한 방법을 제공합니다. 이번 글에서는 파일과 폴더를 삭제하는 방법에 대해 알아보겠습니다.
1. os 모듈 사용하기
os 모듈을 사용하여 파일과 폴더를 삭제할 수 있습니다. remove() 함수를 사용하여 파일을 삭제하고, rmdir() 함수를 사용하여 폴더를 삭제할 수 있습니다.
import os
file_path = 'example.txt'
folder_path = 'my_folder'
# 파일 삭제
if os.path.exists(file_path):
os.remove(file_path)
print(f"{file_path} is deleted.")
else:
print(f"{file_path} does not exist.")
# 폴더 삭제
if os.path.exists(folder_path):
os.rmdir(folder_path)
print(f"{folder_path} is deleted.")
else:
print(f"{folder_path} does not exist.")
2. shutil 모듈 사용하기
shutil 모듈은 파일 및 폴더를 더 쉽게 삭제할 수 있는 함수를 제공합니다. remove() 함수는 파일을, rmtree() 함수는 폴더를 삭제합니다.
import shutil
file_path = 'example.txt'
folder_path = 'my_folder'
# 파일 삭제
if os.path.exists(file_path):
os.remove(file_path)
print(f"{file_path} is deleted.")
else:
print(f"{file_path} does not exist.")
# 폴더 삭제
if os.path.exists(folder_path):
shutil.rmtree(folder_path)
print(f"{folder_path} is deleted.")
else:
print(f"{folder_path} does not exist.")
'프로그래밍' 카테고리의 다른 글
[Python/파이썬]float을 String으로 변환하기 (0) | 2024.03.05 |
---|---|
[Python/파이썬] 폴더의 모든 파일 리스트 가져오기 (0) | 2024.03.05 |
[Python/파이썬] 파일, 폴더 존재 유무 확인 (0) | 2024.03.05 |
[Python/파이썬] 딕셔너리의 요소(key, value) 출력 방법 (0) | 2024.03.05 |
[Python/파이썬] 반복문으로 딕셔너리(dict) 순회하기 (0) | 2024.03.05 |