Python os 모듈을 활용한 파일 시스템 제어 및 경로 관리

1. 현재 파일 및 상위 디렉토리 경로 추출

Python 스크립트를 작성할 때 현재 실행 중인 파일의 위치를 기준으로 경로를 설정해야 하는 경우가 많습니다. __file__ 예약어와 os.path.dirname을 조합하여 이를 수행할 수 있습니다.

import os

# 현재 파일이 위치한 디렉토리
current_path = os.path.dirname(__file__)

# 현재 파일의 상위 디렉토리
parent_path = os.path.dirname(current_path)

# 현재 파일의 상위의 상위 디렉토리
grandparent_path = os.path.dirname(parent_path)

print(f"현재 위치: {current_path}")
print(f"상위 위치: {parent_path}")

2. 시스템 정보 및 작업 디렉토리 확인

실행 환경의 OS 종류나 현재 작업 중인 디렉토리를 확인하는 기본 함수들입니다.

  • os.name: 실행 중인 OS를 확인합니다. Windows는 'nt', Linux/macOS는 'posix'를 반환합니다.
  • os.getcwd(): 현재 작업 디렉토리(Current Working Directory)를 반환합니다.
  • os.chdir(path): 작업 디렉토리를 지정한 경로로 변경합니다.

3. 파일 및 디렉토리 조작

파일 시스템을 직접 제어하기 위한 핵심 기능들입니다.

  • os.listdir(path): 해당 경로 내의 모든 파일과 폴더 목록을 리스트로 반환합니다.
  • os.mkdir(path): 폴더를 하나 생성합니다. 상위 폴더가 없으면 에러가 발생합니다.
  • os.makedirs(path): 중간 단계의 디렉토리가 없더라도 재귀적으로 모든 경로를 생성합니다.
  • os.remove(path): 파일을 삭제합니다.
  • os.rmdir(path): 비어 있는 디렉토리를 삭제합니다.

4. 경로 유효성 검사 및 분석

경로가 파일인지, 디렉토리인지, 혹은 존재하는지 여부를 판단합니다.

path_target = "/home/dev/workspace/sample.txt"

print(os.path.exists(path_target))  # 존재 여부 확인
print(os.path.isfile(path_target))  # 파일 여부 확인
print(os.path.isdir(path_target))   # 디렉토리 여부 확인

# 경로와 파일명 분리
directory, filename = os.path.split(path_target)
print(f"디렉토리: {directory}, 파일명: {filename}")

# 파일 확장자 제외한 베이스 이름과 경로 추출
print(os.path.basename(path_target)) # sample.txt
print(os.path.dirname(path_target))  # /home/dev/workspace

5. 경로 결합 및 절대 경로 변환

운영체제마다 다른 경로 구분자(/ 또는 \)를 신경 쓰지 않고 안전하게 경로를 결합하려면 os.path.join을 사용해야 합니다.

base_dir = "/usr/local/bin"
file_name = "python3"

# 안전한 경로 결합
full_path = os.path.join(base_dir, file_name)
print(full_path) # /usr/local/bin/python3

# 상대 경로를 절대 경로로 변환
relative_path = "./logs/error.log"
print(os.path.abspath(relative_path))

6. 시스템 명령 실행 및 환경 변수 활용

Python 내부에서 쉘 명령을 실행하거나 환경 변수를 설정할 수 있습니다.

# 시스템 명령어 실행
os.system("ls -al") 

# 환경 변수 설정 및 활용
os.environ['APP_LEVEL'] = 'DEBUG'
level = os.getenv('APP_LEVEL')
print(f"현재 설정된 레벨: {level}")

7. 응용: 특정 디렉토리에서 가장 최근에 수정된 파일 찾기

파일의 수정 시간(mtime)을 조회하는 os.path.getmtime을 활용하여 최신 파일을 식별하는 예제입니다.

import os

def get_latest_file(directory_path):
    # 디렉토리 내 파일 목록 추출
    files = [os.path.join(directory_path, f) for f in os.listdir(directory_path)]
    
    # 파일만 필터링
    files = [f for f in files if os.path.isfile(f)]
    
    if not files:
        return None
        
    # 수정 시간을 기준으로 정렬
    files.sort(key=lambda x: os.path.getmtime(x), reverse=True)
    
    return files[0]

target_folder = "./reports"
latest = get_latest_file(target_folder)
print(f"최신 리포트 파일: {latest}")

태그: python os-module file-management path-manipulation Scripting

11월 12일 08:56에 게시됨