Notice
Recent Posts
Recent Comments
Link
SeouliteLab
[Python/파이썬] 파일, 폴더 존재 유무 확인 본문
파이썬에서는 파일과 폴더의 존재 여부를 확인하는 다양한 방법을 제공합니다. 이번 글에서는 파일과 폴더가 존재하는지 확인하는 방법에 대해 알아보겠습니다.
1. os.path 모듈 사용하기
os.path 모듈은 파일 시스템 경로를 다루는 함수들을 제공합니다. exists() 함수를 사용하여 파일이나 폴더의 존재 여부를 확인할 수 있습니다.
import os
path_to_file = 'example.txt'
path_to_folder = 'my_folder'
# 파일 존재 여부 확인
if os.path.exists(path_to_file):
print(f"{path_to_file} exists.")
else:
print(f"{path_to_file} does not exist.")
# 폴더 존재 여부 확인
if os.path.exists(path_to_folder):
print(f"{path_to_folder} exists.")
else:
print(f"{path_to_folder} does not exist.")
2. pathlib 모듈 사용하기
pathlib 모듈은 객체 지향적인 방식으로 파일 시스템 경로를 다룰 수 있습니다. exists() 메서드를 사용하여 파일이나 폴더의 존재 여부를 확인할 수 있습니다.
from pathlib import Path
path_to_file = Path('example.txt')
path_to_folder = Path('my_folder')
# 파일 존재 여부 확인
if path_to_file.exists():
print(f"{path_to_file} exists.")
else:
print(f"{path_to_file} does not exist.")
# 폴더 존재 여부 확인
if path_to_folder.exists():
print(f"{path_to_folder} exists.")
else:
print(f"{path_to_folder} does not exist.")
'프로그래밍' 카테고리의 다른 글
[Python/파이썬] 폴더의 모든 파일 리스트 가져오기 (0) | 2024.03.05 |
---|---|
[Python/파이썬] 파일, 폴더 삭제 (0) | 2024.03.05 |
[Python/파이썬] 딕셔너리의 요소(key, value) 출력 방법 (0) | 2024.03.05 |
[Python/파이썬] 반복문으로 딕셔너리(dict) 순회하기 (0) | 2024.03.05 |
[Python/파이썬] 딕셔너리에 key가 있는지 확인하기 (0) | 2024.03.05 |