반응형

pathlib 모듈은 파이썬 표준 라이브러리로, 파일 읽기/쓰기 작업이나 디렉토리에 있는 특정 유형 파일 나열, 특정 파일의 상위 디렉토리 찾기 등의 작업을 할 때 사용됨

The Problem With Representing Paths as Strings

  • python 3.4 버전부터 pathlib 모듈이 등장했는데 pathlib이 존재하기 전에는 전통적으로 string을 이용하여 파일 경로를 표현했음
  • 하지만 경로는 일반 문자열 이상이기 때문에 중요한 기능들이 os, glob, shutil과 같은 라이브러리를 포함한 표준 라이브러리 전체에 분산되어 있었음
  • 예를 들어 아래의 코드는 txt 파일을 하위의 archive 폴더로 이동시키는 내용
import glob
import os
import shutil

for file_name in glob.glob("*.txt"):
    new_path = os.path.join("archive", file_name)
    shutil.move(file_name, new_path)
  • glob, os, shutil 까지 3개의 import statement 필요
  • pathlib 모듈은 여러 운영체제에서 동일한 방식으로 작동하는 Path 클래스를 제공해 위 3가지 모듈은 임포트 하는 대신 pathlib 모듈만 사용하여 동일한 작업을 수행할 수 있음
from pathlib import Path

for file_path in Path.cwd().glob("*.txt"):
    new_path = Path("archive") / file_path.name
    file_path.replace(new_path)

Path Instantiation With Python’s pathlib

  • pathlib 모듈에 대해 한가지 강력한 동기는 string 대신 전용 객체로 파일 시스템을 표현하는 것
  • 객체 지향 접근 방식은 기존 os.path 방식과 대조할 때, pathlib 핵심이 Path 클래스 라는 점에 주목하면 더욱 분명함
>>> from pathlib import Path
>>> Path
<class 'pathlib.Path'>
  • Path 클래스로 작업하기 때문에 import pathlib; pathlib.Path 보다 from pathlib import Path로 작업하는게 더 효율적
  • Path 객체를 인스턴스화 하는 방법에는 몇가지가 있지만 이 글에서는 클래스 메소드, 문자열 전달, path 컴포넌트를 조인함으로써 path 객체를 생성하는 것을 살펴봄

Using Path Methods

  • Path를 import 한 후에 working directory나 home directory를 가져오기 위해 기존 메소드를 사용할 수 있음
>>> from pathlib import Path
>>> Path.cwd()
PosixPath('/Users/woo-seongchoi/Desktop/realpython')
  • pathlib.Path를 인스턴스로 만들면, OS에 따라 WindowsPath나 PosixPath 객체를 얻을 수 있음
  • 일반적으로 Path를 사용하면, 사용중인 플랫폼에 대한 구체적인 경로를 인스턴스화하는 동시에 코드가 플랫폼에 독립적으로 유지됨
>>> from pathlib import Path
>>> Path.home()
PosixPath('/Users/woo-seongchoi')
  • Path 객체의 cwd나 home 메소드를 통해 python script의 starting point를 쉽게 얻을 수 있음

Passing in a String

  • home directory나 current working directory 대신에 string을 Path 에 전달함으로써 directory나 file을 가리킬 수 있음
>>> from pathlib import Path
>>> Path("/Users/woo-seongchoi/Desktop/realpython/file.txt")
PosixPath('/Users/woo-seongchoi/Desktop/realpython/file.txt')
  • Path 객체를 생성하고 string을 다루는 대신 pathlib 모듈이 제공하는 유연성을 통해 작업 가능
  • POSIX는 Portable Operating System Interface 이고, path 표현 등을 포함하여 운영 체제간 호환성을 유지하기 위한 표준임

Joining Paths

  • 슬래시 (’/’) 를 이용하여 경로의 일부를 연결하도록 경로를 구성할 수 있음
from pathlib import Path

for file_path in Path.cwd().glob("*.txt"):
    new_path = Path("archive") / file_path.name
    file_path.rename(new_path)
  • 슬래시 연산자는 Path 객체를 포함하는 한 여러 경로 또는 경로와 문자열이 섞인 경우도 결합시킬 수 있음
  • 슬래시 연산자를 사용하지 않는다면 joinpath 메소드를 사용할 수 있음
>>> from pathlib import Path
>>> Path.home().joinpath("python", "scripts", "test.py")
PosixPath('/home/woo-seongchoi/python/scripts/test.py')

References

https://realpython.com/python-pathlib/

 

 

반응형

+ Recent posts