File System - os, os.path, shutil

os 와 os.path 모듈은 파일 시스템에 관련된 작업을 하기 위한 많은 함수들을 제공한다.

shutil 모듈을 이용하여 파일들을 복사할 수 있다.

함수 설명
os.listdir(dir) dir 에 있는 파일이름들의 리스트 (. 와 .. 를 포함하지 않는다). 파일이름들은 디렉토리에서의 이름으로, 절대 경로가 아니다.
os.path.join(dir, filename) 위에서 받은 형태의 filename 과 dir 을 합쳐서 path 를 만든다
os.path.abspath(path) path 를 받아서, 절대 경로를 리턴한다. /home/nick/foo/bar.html 처럼 말이다
os.path.dirname(path)os.path.basename(path) dir/foo/bar.html 을 받아서, dirname "dir/foo" 와 basename "bar.html" 을 리턴한다
os.path.exists(path) path 가 존재하면 true 를 리턴한다
os.mkdir(dir_path) dir 하나를 만든다, os.makedirs(dir_path) 는 dir_path 를 만들기 위한 모든 디렉토리들을 만든다
shutil.copy(source-path, dest-path) 파일을 복사한다 (복사될 파일의 디렉토리가 존재해야 한다)

예제코드

dir 에서 filename 들을 가져와서, 상대 경로와 절대경로를 프린트한다

import os

def print_dir(dir): 
    file_names = os.listdir(dir) 
    for filename in file_names: 
        print(filename)

        ## foo.txt print os.path.join(dir, filename) 
        ## dir/foo.txt (현재 디렉토리에 상대 경로) 
        ## /home/nick/dir/foo.txt
        print(os.path.abspath(os.path.join(dir, filename))) 

if __name__ == "__main__":
    print_dir(".")

results matching ""

    No results matching ""