본문으로 바로가기

해당 경로의 디렉터리 경로 os.path.dirname(path)

해당 경로의 디렉터리 경로를 구합니다.

print('dir')
dir_path = os.getcwd()
print(dir_path)
dir_name = os.path.dirname(dir_path)
print(dir_name)

print('file')
file_path = os.path.abspath(__file__)
print(file_path)
dir_name = os.path.dirname(file_path)
print(dir_name)
더보기
dir
C:\Users\Desktop\Reference\Example\ex_os
C:\Users\Desktop\Reference\Example
file
c:\Users\Desktop\Reference\Example\ex_os\ex3.py
c:\Users\Desktop\Reference\Example\ex_os

 

해당 경로의 디렉터리/파일명 os.path.basename(path)

해당 경로의 디렉터리명 혹은 파일명을 구합니다.

print('dir')
dir_path = os.getcwd()
print(dir_path)
basename = os.path.basename(dir_path)
print(basename)

print('file')
file_path = os.path.abspath(__file__)
print(file_path)
basename = os.path.basename(file_path)
print(basename)
더보기
dir
C:\Users\Desktop\Reference\Example\ex_os
ex_os
file
c:\Users\Desktop\Reference\Example\ex_os\ex3.py
ex3.py

 

경로를 한번에 분리 os.path.split(path)

split() 은 디렉터리 경로와 디렉터리/파일명을 한번에 반환합니다.

print('dir')
dir_path = os.getcwd()
print(dir_path)
dirname, basename = os.path.split(dir_path)
print(dirname)
print(basename)

print('file')
file_path = os.path.abspath(__file__)
print(file_path)
dirname, basename = os.path.split(file_path)
print(dirname)
print(basename)
더보기
dir
C:\Users\Desktop\Reference\Example\ex_os
C:\Users\Desktop\Reference\Example
ex_os
file
c:\Users\Desktop\Reference\Example\ex_os\ex3.py
c:\Users\Desktop\Reference\Example\ex_os
ex3.py

 

파일명과 확장자 분리 os.path.splitext(path)

splitext() 은 파일명을 이름과 확장자로 분리해서 반환합니다.

마지막 확장자가 포함된 파일명을 주었을 경우에만 정상적으로 반환되었습니다.

print('dir')
dir_path = os.getcwd()
name, ext = os.path.splitext(dir_path)
print('name :', name)
print('ext :', ext)

print('file')
file_path = os.path.abspath(__file__)
print('name :', name)
print('ext :', ext)

basename = os.path.basename(file_path)
name, ext = os.path.splitext(basename)
print('name :', name)
print('ext :', ext)
더보기
dir
name : C:\Users\Desktop\Reference\Example\ex_os
ext :
file
name : C:\Users\Desktop\Reference\Example\ex_os
ext :
name : ex3
ext : .py

 

응용

 

파이썬 파이큐티(PyQT5) 앱 만들기 : 분리수거 - 1

소개 및 기능 분리수거 앱은 폴더를 열어 확장자별로 파일을 분류해주며 이동, 복사, 삭제 기능을 수행할 수 있습니다. 중복된 파일은 따로 폴더를 생성해서 넘버링합니다. 파일 찾기에는 적합��

jvvp.tistory.com