본문 바로가기
프로그래밍 언어/Python

[python] 디렉토리 관련 명령어

by nahkim 2024. 5. 27.
 
>>> import os

# 현재 작업하고 있는 경로
>>> os.getcwd()

# path 경로에 있는 파일 및 폴더 목록 리스트화(매개변수가 없는 경우 현재 실행하고 있는 위치의 파일 목록 보여줌)
os.listdir([path])

# file의 이름과 확장자를 tuple형태로 나타냄
os.path.splitext(<file>)
 

 

사용 예시

 
>>> import os
# 현재 작업하고 있는 경로
>>> os.getcwd()
'/Users/nahkim/Documents/GitHub/TIL'

# path 경로에 있는 파일 및 폴더 목록 리스트화(매개변수가 없는 경우 현재 실행하고 있는 위치의 파일 목록 보여줌)
>>> os.listdir()
['batch.log', 'Tutorial', 'docs', 'test.py', 'README.md', 'setting']
>>> f = os.listdir()[0]
>>> f
'batch.log'
# file의 이름과 확장자를 tuple형태로 나타냄
>>> os.path.splitext(f)
('batch', '.log')
>>> type(os.path.splitext(f))
<class 'tuple'>