Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags more
Archives
Today
Total
관리 메뉴

개발자로 살아남기

[Python] 파이썬 경로 분리하기(파일명만 추출, 파일 확장자만 추출, 경로 추출, 경로와 파일명을 분리 등) 본문

프로그래밍/Python

[Python] 파이썬 경로 분리하기(파일명만 추출, 파일 확장자만 추출, 경로 추출, 경로와 파일명을 분리 등)

UnaUna 2023. 5. 20. 13:43
1. 경로에서 디렉토리 경로만 추출하기 os.path.dirname()
path = "D://test//test2//test_path.png"

directory_name = os.path.dirname(path)
print(directory_name)

결과

D://test//test2

 

2. 경로에서 파일명만 추출하기 os.path.basename()
path = "D://test//test2//test_path.png"

basename = os.path.basename(path)
print(basename)

결과

test_path.png

 

3. 디렉토리 경로와 파일명을 같이 반환 os.path.split()
path = "D://test//test2//test_path.png"

directory, filename = os.path.split(path)
print(f"directory : {directory}")
print(f"filename : {filename}")

결과

directory : D://test//test2
filename : test_path.png

 

4. 파일명과 확장자 분리 os.path.splitext()
path = "D://test//test2//test_path.png"

filename, extension = os.path.splitext(os.path.basename(path))
print(f"filename : {filename}")
print(f"extension : {extension}")

결과

filename : test_path
extension : .png