os 모듈

함수 설명
os.listdir 현재 파일 및 디렉터리 목록을 보여준다.
os.getcwd 현재 디렉터리(current word directory)을 표시한다.
os.path.isdir 디렉터리 존재유무를 알려준다.
os.mkdir 디렉터리 만들어준다.
os.path.join 디렉터리와 디렉터리(파일명)를 결합한다.
os.system 커맨드를 실행한다.
os.popen 커맨드 실행에 대한 파일 객체를 반환한다.
import os

print(os.getcwd()) # 현재 경로
print(os.listdir(os.getcwd())) # 현재 경로에 있는 directory 및 file 목록
print(os.path.isdir("game")) # game directory가 있으면 true 아니면 false
print(os.path.isfile("a.py")) # a.py file이 있으면 true, 아니면 false
os.mkdir("my") # my directory 생성
print(os.path.join(os.getcwd(), "my")) # 현재 경로에 my 결합
os.system('dir') # UNIX는 ls
os.system('notepad') # 메모장 실행

위의 예제 코드와 같이 os를 import함으로써 파일 디렉터리를 보다 수월하게 다룰 수 있다. 

 

import os

s = os.popen("dir").read()
print(s)

예제 코드와 같이 현재 디렉터리 및 현재 디렉터리에 있는 파일 명들을 확인 가능하다. Shell command 실행 결과에 대한 문자열을 얻고 싶으면 popen을 통해 파일 객체를 얻고 read하면 된다.

 

glob 모듈

import glob

print(glob.glob('*.py')) # py 확장자
print(glob.glob('[abc]*.py')) # a or b or c로 시작되는 py 확장자

 

glob은 파일에 대해 필터링 할 때 활용된다.

 

 

+ Recent posts