Published on

Python으로 경로 다루기(os와 pathlib 모듈 비교)

Authors

파일과 디렉토리, 경로 등 Path를 다루는 것은 개발환경을 세팅하는데 필수적인 작업인 것 같습니다.

Python에서는 이를 위해 os 모듈과 pathlib 모듈을 제공합니다. 두 모듈을 사용하여 경로를 다루는 방법을 기록합니다.

1. os

import os

print("현재 작업중인 디렉토리 출력 : ", os.getcwd())
print("현재 작업중인 디렉토리 내부 : ", os.listdir(os.getcwd()))

print(f"현재 파일의 경로 출력 : ", __file__)

file_path = os.path.abspath(__file__)
print(f"현재 파일의 절대 경로 : ", file_path)
print(f"파일이 속한 디렉토리 경로 : ", os.path.dirname(file_path), "or", os.path.dirname(__file__))

print("*" * 100)

# 작업 디렉토리를 변경 (하위 폴더로 이동)
sub_directory_path = os.path.join(os.path.dirname(file_path), "sub_directory")
print("변경된 작업 디렉토리: ", sub_directory_path)
os.chdir(sub_directory_path)

# 상대 경로로 파일 생성
with open("subfile.txt", "w") as f:
    f.write("안녕하세요")

# 상위 폴더로 돌아와서 파일 읽기
os.chdir("..")
with open("sub_directory/subfile.txt", "r") as f:
    content = f.read()
    print(content)

  • os.getcwd(): 현재 작업 디렉토리를 출력합니다.
  • os.listdir(): 디렉토리 내부의 파일 및 폴더 목록을 가져옵니다.
  • os.path.abspath(): 파일의 절대 경로를 얻습니다.
  • os.path.dirname(): 파일이 위치한 디렉토리 경로를 가져옵니다.
  • os.chdir(): 작업 디렉토리를 변경합니다.
  • os.path.join(): 경로를 결합하여 새로운 경로를 만듭니다.

1.1 getcwd != pwd

작업 디렉토리는 현재 실행되는 모듈(파일)의 디렉토리와 다릅니다. Pycharm 등 에서 현재 파일을 실행하는 작업의 디렉토리를 의미 합니다.

따라서, 위의 코드에서 __file__ 이 위치한 디렉토리와 getcwd() 를 통해 가져온 경로가 다를 수 있음에 유의해야 할 것 같습니다.

2. pathlib

pathlib을 사용하면 코드가 더 직관적이고 읽기 쉬워집니다.

from pathlib import Path
import os

# 현재 파일이 위치한 디렉토리 경로
directory_path = Path(os.path.dirname(__file__))
print("현재 디렉토리 경로: ", directory_path)

# 디렉토리 내부의 파일 및 폴더 목록
all_files_folders = list(directory_path.iterdir())
print("디렉토리 내부의 파일 및 폴더 목록: ", all_files_folders)

print("*" * 100)

# 파일만 가져오기
only_files = [f for f in directory_path.iterdir() if f.is_file()]
print("파일만 가져오기: ", only_files)

# 폴더만 가져오기
only_folders = [f for f in directory_path.iterdir() if f.is_dir()]
print("폴더만 가져오기: ", only_folders)

# 재귀적으로 모든 파일 가져오기
directory_path = directory_path.parent
all_files = list(directory_path.rglob("*"))
print("재귀적으로 모든 파일 가져오기: ", all_files)

# 파일 필터링
import glob
files = glob.glob(f"{directory_path}/*.py")  # .py 파일만 나열
print("필터링된 파일: ", files)

  • Path(): Path 객체를 생성하여 디렉토리와 파일을 객체 지향적으로 다룹니다.
  • Path().iterdir(): 디렉토리 내부의 파일과 폴더 목록을 가져옵니다.
  • Path().is_file(): 파일인지 확인합니다.
  • Path().is_dir(): 디렉토리인지 확인합니다.
  • Path().rglob(): 재귀적으로 모든 파일을 검색합니다.
  • glob.glob(): 패턴에 맞는 파일을 필터링하여 리스트로 반환합니다.

3. ospathlib 비교

기능os 모듈pathlib 모듈
경로 결합os.path.join()Path().joinpath()
디렉토리 목록os.listdir()Path().iterdir()
파일 확인os.path.isfile() / os.path.isdir()Path().is_file() / Path().is_dir()
재귀 탐색os.walk()Path().rglob()
패턴 필터링glob.glob()Path().glob()

ospathlib 모듈을 통해 경로를 다루는 방법과 간단한 메서드를 테스트 해봤습니다.

Path객체를 사용하여 개발하는 것이 객체 지향적인 접근 방식으로 개발하는 좋은 예시 같습니다.

hongreat 블로그의 글을 봐주셔서 감사합니다! 하단의 버튼을 누르시면 댓글을 달거나 보실 수 있습니다.

Buy Me A Coffee