Python 에서 파일 존재 여부 확인하는 방법

PythonBeginner
지금 연습하기

소개

이 랩에서는 Python 에서 다양한 방법을 사용하여 파일이 존재하는지 확인하는 방법을 배우게 됩니다. 랩은 파일 경로에 대한 소개로 시작하며, 절대 경로와 상대 경로의 차이점을 설명합니다. 샘플 텍스트 파일과 Python 스크립트를 생성하여 현재 작업 디렉토리를 얻고 파일에 대한 상대 경로와 절대 경로를 모두 정의하는 방법을 시연합니다.

그런 다음 랩에서는 os.path.exists() 함수와 pathlib.Path 객체를 사용하여 파일의 존재 여부를 확인하는 방법을 안내합니다. 이러한 방법은 파일에서 읽거나 쓰기를 시도하기 전에 파일이 존재하는지 확인하는 신뢰할 수 있는 방법을 제공하여 Python 프로그램에서 잠재적인 오류를 방지합니다.

파일 경로 소개

이 단계에서는 Python 에서 파일 경로의 개념을 살펴보겠습니다. 파일 경로를 이해하는 것은 파일에서 읽고 쓰고, Python 프로그램 내에서 파일 시스템을 탐색하는 데 매우 중요합니다.

파일 경로는 기본적으로 컴퓨터에서 파일 또는 디렉토리의 주소입니다. 파일 경로는 크게 두 가지 유형이 있습니다.

  • 절대 경로 (Absolute paths): 이러한 경로는 파일 시스템의 루트 디렉토리부터 시작하여 파일 또는 디렉토리의 전체 위치를 제공합니다. 예를 들어, Linux 시스템에서 절대 경로는 /home/labex/project/my_file.txt와 같이 보일 수 있습니다.
  • 상대 경로 (Relative paths): 이러한 경로는 현재 작업 디렉토리를 기준으로 파일 또는 디렉토리의 위치를 지정합니다. 예를 들어, 현재 작업 디렉토리가 /home/labex/project인 경우 상대 경로 my_file.txt는 절대 경로 /home/labex/project/my_file.txt와 동일한 파일을 참조합니다.

VS Code 편집기를 사용하여 ~/project 디렉토리에 간단한 텍스트 파일을 만들어 보겠습니다. my_file.txt라는 새 파일을 만들고 다음 내용을 추가합니다.

Hello, LabEx!
This is a test file.

~/project 디렉토리에 파일을 저장합니다.

이제 이 파일과 상호 작용하는 Python 스크립트를 만들어 보겠습니다. 동일한 ~/project 디렉토리에 file_paths.py라는 새 파일을 만들고 다음 코드를 추가합니다.

import os

## Get the current working directory
current_directory = os.getcwd()
print("Current working directory:", current_directory)

## Define a relative path to the file
relative_path = "my_file.txt"
print("Relative path:", relative_path)

## Define an absolute path to the file
absolute_path = os.path.join(current_directory, relative_path)
print("Absolute path:", absolute_path)

이 스크립트에서:

  • 운영 체제와 상호 작용하기 위한 함수를 제공하는 os 모듈을 가져옵니다.
  • os.getcwd()를 사용하여 현재 작업 디렉토리를 가져옵니다.
  • my_file.txt 파일에 대한 상대 경로를 정의합니다.
  • os.path.join()을 사용하여 현재 작업 디렉토리와 상대 경로를 결합하여 절대 경로를 만듭니다.

이제 스크립트를 실행해 보겠습니다. VS Code 에서 터미널을 열고 ~/project 디렉토리로 이동합니다 (기본적으로 이미 해당 디렉토리에 있을 것입니다). 그런 다음 다음 명령을 사용하여 스크립트를 실행합니다.

python file_paths.py

다음과 유사한 출력을 볼 수 있습니다.

Current working directory: /home/labex/project
Relative path: my_file.txt
Absolute path: /home/labex/project/my_file.txt

이것은 현재 작업 디렉토리를 얻고 Python 에서 상대 및 절대 파일 경로를 모두 구성하는 방법을 보여줍니다. 이러한 개념을 이해하는 것은 Python 프로그램에서 파일 및 디렉토리를 사용하는 데 필수적입니다.

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()를 사용하여 파일 및 디렉토리의 존재 여부를 확인하는 방법을 보여줍니다. 파일에서 읽거나 쓰기를 시도하기 전에 이 단계를 수행하는 것은 오류를 방지하고 프로그램이 예상대로 작동하도록 하는 데 매우 중요합니다.

pathlib.Path 로 확인

이 단계에서는 파일 및 디렉토리와 상호 작용하는 객체 지향적인 방법을 제공하는 pathlib 모듈을 살펴보겠습니다. 특히 pathlib.Path를 사용하여 파일 및 디렉토리의 존재 여부를 확인하고, os.path.exists()의 대안을 제공하는 데 중점을 두겠습니다.

pathlib 모듈은 이전 os.path 모듈에 비해 파일 경로 조작에 대한 보다 현대적이고 직관적인 접근 방식을 제공합니다. 파일 경로를 객체로 나타내므로 해당 객체의 메서드를 사용하여 다양한 작업을 수행할 수 있습니다.

pathlib.Path를 사용하도록 지금까지 작업해 온 file_paths.py 스크립트를 수정해 보겠습니다. VS Code 편집기에서 file_paths.py 파일을 열고 다음 코드를 추가합니다.

import os
from pathlib import Path

## 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)

## Create Path objects for relative and absolute paths
relative_path_obj = Path(relative_path)
absolute_path_obj = Path(absolute_path)

## Check if the file exists using the relative path object
if relative_path_obj.exists():
    print("The relative path 'my_file.txt' exists (using pathlib).")
else:
    print("The relative path 'my_file.txt' does not exist (using pathlib).")

## Check if the file exists using the absolute path object
if absolute_path_obj.exists():
    print("The absolute path", absolute_path, "exists (using pathlib).")
else:
    print("The absolute path", absolute_path, "does not exist (using pathlib).")

## Check if a directory exists using pathlib
directory_path_obj = Path(current_directory)
if directory_path_obj.exists():
    print("The directory", current_directory, "exists (using pathlib).")
else:
    print("The directory", current_directory, "does not exist (using pathlib).")

## Check if a non-existent file exists using pathlib
non_existent_file = "non_existent_file.txt"
non_existent_path_obj = Path(non_existent_file)
if non_existent_path_obj.exists():
    print("The file", non_existent_file, "exists (using pathlib).")
else:
    print("The file", non_existent_file, "does not exist (using pathlib).")

이 스크립트에서:

  • pathlib 모듈에서 Path 클래스를 가져옵니다.
  • my_file.txt에 대한 상대 경로와 절대 경로 모두에 대해 Path 객체를 생성합니다.
  • Path 객체의 exists() 메서드를 사용하여 파일이 존재하는지 확인합니다.
  • 또한 pathlib을 사용하여 현재 디렉토리와 존재하지 않는 파일의 존재 여부를 확인합니다.

이제 스크립트를 다시 실행해 보겠습니다. VS Code 에서 터미널을 열고 다음 명령을 사용하여 스크립트를 실행합니다.

python file_paths.py

다음과 유사한 출력을 볼 수 있습니다.

The relative path 'my_file.txt' exists (using pathlib).
The absolute path /home/labex/project/my_file.txt exists (using pathlib).
The directory /home/labex/project exists (using pathlib).
The file non_existent_file.txt does not exist (using pathlib).

이것은 파일 및 디렉토리의 존재 여부를 확인하기 위해 os.path.exists()의 대안으로 pathlib.Path를 사용하는 방법을 보여줍니다. pathlib 모듈은 Python 에서 파일 경로와 상호 작용하는 보다 객체 지향적이고 종종 더 읽기 쉬운 방법을 제공합니다.

요약

이 랩에서는 Python 에서 파일 경로의 개념을 탐구하는 것으로 시작하여 절대 경로와 상대 경로를 구분했습니다. 절대 경로는 파일의 전체 위치를 제공하고, 상대 경로는 현재 작업 디렉토리를 기준으로 한 위치를 지정한다는 것을 배웠습니다.

그런 다음 my_file.txt라는 텍스트 파일과 file_paths.py라는 Python 스크립트를 생성하여 os.getcwd()를 사용하여 현재 작업 디렉토리를 얻는 방법과 os 모듈을 사용하여 생성된 파일에 대한 상대 경로와 절대 경로를 모두 정의하는 방법을 시연했습니다.