CS/python
[python] 특정 경로가 없을 때 디렉토리를 생성하는 방법
judy@
2022. 9. 27. 14:20
target_dir 경로에 뭔가를 저장하려고 했는데, 이 경로가 없어서 오류가 발생하면,
저장 이전에 다음 명령어를 통해 디렉토리를 생성해주면 된다.
if not os.path.exists(target_dir): os.mkdir(target_dir)
위를 응용하여, working directory에 오늘 날짜의 디렉토리를 생성하고 싶을 때는 다음과 같이 생성할 수 있다.
import os
from datetime import datetime as dt
date = dt.strftime(dt.now(), '%y-%m-%d')
target_dir = f'./{date}'
if not os.path.exists(target_dir): os.mkdir(target_dir)
반응형