[파이썬] os 경로와 파일명 분리: `os.path.basename()`, `os.path.dirname()`

Python의 os.path 모듈은 파일 경로와 관련된 작업을 쉽게 수행할 수 있게 해줍니다. 이 모듈을 사용하면 파일 경로에서 경로와 파일명을 분리하는 작업을 간단하게 처리할 수 있습니다. 이를 위해 os.path.basename()os.path.dirname() 함수를 사용할 수 있습니다.

os.path.basename()

os.path.basename() 함수는 파일 경로에서 파일명만 반환합니다. 이는 파일 경로에서 파일명을 쉽게 추출하는데 유용합니다. 아래의 예제를 살펴보겠습니다.

import os

file_path = '/User/Documents/file.txt'
file_name = os.path.basename(file_path)

print(file_name)

결과는 다음과 같이 출력됩니다.

file.txt

os.path.dirname()

os.path.dirname() 함수는 파일 경로에서 경로 부분만 반환합니다. 이는 파일 경로에서 경로를 추출하는데 유용합니다. 아래의 예제를 살펴보겠습니다.

import os

file_path = '/User/Documents/file.txt'
directory = os.path.dirname(file_path)

print(directory)

결과는 다음과 같이 출력됩니다.

/User/Documents

위의 예제를 통해 알 수 있듯이, os.path.basename() 함수는 파일 경로의 마지막 요소인 파일명을 반환하고, os.path.dirname() 함수는 파일 경로에서 파일명을 제외한 부분을 반환합니다.

이러한 함수들을 사용하여 파일 경로와 파일명을 쉽게 분리할 수 있으며, 이를 통해 파일 경로와 관련된 작업을 효율적으로 수행할 수 있습니다.