[파이썬] 파일의 디렉토리 내 파일 분리

파일 처리는 프로그램 개발과 데이터 분석에 있어 중요한 부분입니다. 이번에는 파일의 디렉토리 내 파일 분리에 대해 알아보겠습니다.

파이썬은 다양한 파일 처리 기능을 제공하며, 파일의 디렉토리 내 파일을 분리하는 방법도 간단합니다. 디렉토리 내 파일을 분리해야 하는 상황이 있다면 다음과 같은 방법을 사용해보세요.

1. 디렉토리 경로와 파일 이름 분리

파일의 디렉토리 경로와 파일 이름을 분리하기 위해서는 os.path 모듈을 사용합니다. 아래의 예제 코드는 os.path.split() 함수를 사용하여 디렉토리 경로와 파일 이름을 분리하는 방법을 보여줍니다.

import os

file_path = '/path/to/file.txt'

directory, filename = os.path.split(file_path)

print("Directory:", directory)
print("Filename:", filename)

출력 결과는 다음과 같습니다.

Directory: /path/to
Filename: file.txt

2. 파일 확장자 분리

파일의 확장자를 분리하기 위해서는 os.path.splitext() 함수를 사용할 수 있습니다. 아래의 예제 코드는 파일 경로에서 파일 이름과 확장자를 분리하는 방법을 보여줍니다.

import os

file_path = '/path/to/file.txt'

filename, file_extension = os.path.splitext(file_path)

print("Filename:", filename)
print("Extension:", file_extension)

출력 결과는 다음과 같습니다.

Filename: /path/to/file
Extension: .txt

3. 파일 이름과 확장자 분리

파일 이름과 확장자를 분리하는 경우에는 os.path.splitext() 함수와 같이 사용하면 됩니다. 아래의 예제 코드는 파일 경로에서 파일 이름과 확장자를 분리하는 방법을 보여줍니다.

import os

file_path = '/path/to/file.txt'

directory, file_name_ext = os.path.split(file_path)
file_name, file_ext = os.path.splitext(file_name_ext)

print("Directory:", directory)
print("Filename:", file_name)
print("Extension:", file_ext)

출력 결과는 다음과 같습니다.

Directory: /path/to
Filename: file
Extension: .txt

위의 방법들을 사용하여 파일의 디렉토리 내 파일을 분리할 수 있습니다. 파이썬의 파일 처리 기능을 잘 활용하여 데이터를 처리하고 파일을 관리하는 프로그램을 개발해보세요!