본문 바로가기
programming/python

python3 - 파일 경로, 확장자 처리

by sniffer-k 2023. 6. 19.

파이썬 프로그래밍 과정에서 파일 경로,파일 이름, 확장자 이름 파싱에서 주로 사용하는 코드는 다음과 같다

 

python 파일/폴더 경로 파싱

 

  • os.path.basename() : 대상 문자열  오른쪽에서부터 '\' 까지를 반환
    • 전체 경로에서 파일 이름 추출시 사용  
  • os.path.splitext()       : 대상 문자열 '.' 기준으로 반환 (리턴 개수에 따라 순차적으로 반환)
    • 파일 이름에서 확장자와 파일이름을 분리할때 사용

 

샘플 코드는 다음과 같다

import os, subprocess

dir_result = os.getcwd()	#현재 파이썬 코드의 실행 경로를 보여줌

print('getcwd() :' + dir_result)			#

# /Users/user/Desktop/tistory/python/directory

#file full path
file_full_path = dir_result + '/saved-photo.txt'

file_name, file_ext = os.path.splitext(file_full_path)

print('file_name :' + file_name)	# 풀 경로 + 파일 이름
print('file_ext  :' + file_ext)		# .붙이고 확장자

basename = os.path.basename(file_full_path)
name,ext = os.path.splitext(basename)

print('basename :' + basename)
print('name     :' + name)
print('ext      :' + ext)

# file_name :/Users/user/Desktop/tistory/python/directory/saved-photo
# file_ext  :.txt
# basename :saved-photo.txt
# name     :saved-photo
# ext      :.txt

 

728x90