Skip to content

Python:os

path

python 에서 경로처리에 관한 모듈은 os.path를 사용한다.

디렉토리/파일명/확장자

디렉토리/파일명/확장자 획득을 위해 아래의 함수를 사용한다.

  • split
  • splitdrive
  • splitext

Extension name

s = os.path.splitext("/My Jukebox/Cool Jazz.mp3")
print s[1]  # .mp3

Drive name

# 드라이브명까지 포함된 Windows 전용 패스를 취급
s = os.path.splitdrive("D:/My Jukebox/Cool Jazz.mp3")
print s[0]  # D:

Example

입력받은 경로가 존재하면 True를 반환하고, 존재하지 않는 경우는 False를 반환. 리눅스와 같은 OS에서는 파일이나 디렉터리가 존재하지만 읽기 권한이 없는 경우에도 False를 반환할 수 있다.

os.path.exists(path)

현재 실행되는 스크립트파일의 절대경로를 구하려면

os.path.dirname(os.path.abspath( __file__ ))

확장자명을 포함한 파일이름을 획득

os.path.basename(path)

두 경로의 상대적 경로 구하기

os.path.relpath( "c:\\ik" , "c:\\os\\pp" )
# ..\\..\\ik'

공통경로 구하기

os.path.commonprefix( ["c:\\ik\\jj" , "c:\\ik\\sd" ])
# c:\\ik\\'

중간 경로 슬래쉬 제거

os.path.normpath( "c:\\os\\..\\pp" )
# c:\\pp'

현재 실행경로 구하기

os.getcwd()

경로명 합치기

os.path.join( "a" , "b" ,"c" )
# 'a/b/c'

walk

Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).

Find files recursively

Use os.walk to recursively walk a directory and fnmatch.filter to match against a simple expression:

import fnmatch
import os

matches = []
for root, dirnames, filenames in os.walk('src'):
  for filename in fnmatch.filter(filenames, '*.c'):
    matches.append(os.path.join(root, filename))

Example

import os
for p, s, f in os.walk('.'):
    print(p)
    print(s)
    print(f)
    print('------')

다음과 같이 출력된다:

.
['src', 'etc', 'var', 'bin', 'tparty', '.git']
['LICENSE', '.gitignore', 'install.sh', 'INFORMATION', '.gitattributes', 'profile.sh', 'README.md']
------
./src
['opwm']
[]
------
./src/opwm
[]
['dwm.h', '.gitignore', 'util.c', 'install.sh', 'draw.h', 'dwm.c', 'draw.c', 'util.h', 'CMakeLists.txt', 'wmname.c']
------
./etc
['nodejs', 'gdb', 'dependencies', 'tmux', 'coturn', 'conky', 'qtile', 'picom', 'hyper', 'profile.d', 'git', 'xmobar', 'alacritty', 'docker', 'xmonad', 'clang-format', 'n', 'font', 'swarm', 'crawling', 'cuda', 'lldb', 'ffmpeg', 'rust', 'vim', 'eclipse', 'i3', 'x11', 'install.d']
[]
------
...

Get-Print Environment Variable

import os
s = os.environ['PATH']
print s

Troubleshooting

FileNotFoundError in os.getcwd

os.getcwd() 에서 FileNotFoundError가 발생될 경우가 있다. 모종의 이유로 (e.g. 다른 프로세스에서, etc ...) Working Directory 가 제거되면 이러한 현상이 발생된다. os.getcwd() 에서 현재 디렉토리를 검색하는듯 하다.

한마디로 다른 프로세스에서 디렉토리를 제거하는지 확인해 보자.

See also

파일과 디렉터리 액세스

  • Python:pathlib - 객체 지향 파일 시스템 경로
  • Python:os.path - 일반적인 경로명 조작
  • Python:fileinput - 여러 입력 스트림에서 줄을 이터레이트 하기
  • Python:stat - stat() 결과 해석하기
  • Python:filecmp - 파일과 디렉터리 비교
  • Python:tempfile - 임시 파일과 디렉터리 생성
  • Python:glob - 유닉스 스타일 경로명 패턴 확장
  • Python:fnmatch - 유닉스 파일명 패턴 일치
  • Python:linecache - 텍스트 줄에 대한 무작위 액세스
  • Python:shutil - 고수준 파일 연산

Favorite site

References


  1. SystemSection-Python-os-path.pdf