파이썬 프로그래밍 과정에서 파일 경로,파일 이름, 확장자 이름 파싱에서 주로 사용하는 코드는 다음과 같다
- 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
'programming > python' 카테고리의 다른 글
python3 - 판다스 - 데이터프레임 - 수정방법 (0) | 2023.06.18 |
---|---|
python3 - 판다스 - 데이터프레임 (basic) (0) | 2023.06.14 |
python3 with Slack - basic (0) | 2023.06.06 |
python3 - 크롤러 (cloudscraper) (2) | 2023.06.03 |
python - schedule(스케쥴) (0) | 2023.05.29 |