[python] 파일 및 폴더삭제

최승언·2022년 10월 29일
0

python

목록 보기
6/22

1. 파일삭제

import os

file_path = "/tmp/test_3225281795536908985.tmp"

if os.path.exists(file_path):
    os.remove(file_path)

주로 os.path.exists()를 사용해서 해당 파일이 있는지 확인하고 삭제한다.

2. 폴더삭제

import os
import shutil

dir_path = "/tmp/temp_dir2"

if os.path.exists(dir_path):
    shutil.rmtree(dir_path)

원래 os.rmdir이란 함수가 있지만 폴더안이 비어있지 않으면 에러가 나기 때문에 shutil을 사용하는것이 편리하다.

profile
작업하다가 막힌부분을 기록하는 곳.

0개의 댓글