os.path.exists() 사용
이 단계에서는 os.path.exists() 함수를 사용하여 파일 또는 디렉토리가 존재하는지 확인하는 방법을 배우겠습니다. 파일 작업 시 파일이 누락되거나 디렉토리가 존재하지 않는 경우를 처리할 수 있으므로 이는 기본적인 작업입니다.
os.path.exists() 함수는 단일 인수를 사용합니다. 즉, 확인하려는 파일 또는 디렉토리의 경로입니다. 파일 또는 디렉토리가 존재하면 True를 반환하고, 그렇지 않으면 False를 반환합니다.
이전 단계에서 생성한 file_paths.py 스크립트를 수정하여 os.path.exists()를 사용해 보겠습니다. VS Code 편집기에서 file_paths.py 파일을 열고 다음 코드를 추가합니다.
import os
## Get the current working directory
current_directory = os.getcwd()
## Define a relative path to the file
relative_path = "my_file.txt"
## Define an absolute path to the file
absolute_path = os.path.join(current_directory, relative_path)
## Check if the file exists using the relative path
if os.path.exists(relative_path):
print("The relative path 'my_file.txt' exists.")
else:
print("The relative path 'my_file.txt' does not exist.")
## Check if the file exists using the absolute path
if os.path.exists(absolute_path):
print("The absolute path", absolute_path, "exists.")
else:
print("The absolute path", absolute_path, "does not exist.")
## Check if a directory exists
directory_path = current_directory
if os.path.exists(directory_path):
print("The directory", directory_path, "exists.")
else:
print("The directory", directory_path, "does not exist.")
## Check if a non-existent file exists
non_existent_file = "non_existent_file.txt"
if os.path.exists(non_existent_file):
print("The file", non_existent_file, "exists.")
else:
print("The file", non_existent_file, "does not exist.")
이 스크립트에서:
- 상대 경로와 절대 경로를 모두 사용하여
my_file.txt 파일이 존재하는지 확인하기 위해 os.path.exists()를 사용합니다.
- 또한 현재 디렉토리가 존재하는지 확인합니다. 이는 항상 참이어야 합니다.
- 마지막으로, 존재하지 않는 파일이 존재하는지 확인하며, 이는
False를 반환해야 합니다.
이제 스크립트를 다시 실행해 보겠습니다. VS Code 에서 터미널을 열고 다음 명령을 사용하여 스크립트를 실행합니다.
python file_paths.py
다음과 유사한 출력을 볼 수 있습니다.
The relative path 'my_file.txt' exists.
The absolute path /home/labex/project/my_file.txt exists.
The directory /home/labex/project exists.
The file non_existent_file.txt does not exist.
이것은 Python 프로그램에서 os.path.exists()를 사용하여 파일 및 디렉토리의 존재 여부를 확인하는 방법을 보여줍니다. 파일에서 읽거나 쓰기를 시도하기 전에 이 단계를 수행하는 것은 오류를 방지하고 프로그램이 예상대로 작동하도록 하는 데 매우 중요합니다.