# [Python] 2. os.walk

이원규·2023년 1월 7일
0

Python

목록 보기
2/2

os.walk(path)

os.walk(path) 는 인자로 받은 경로에 대해 하위 디렉토리를 검색한다.
디렉토리 구조는 다음과 같을 때,

예제 1): dirs(폴더) & files 구하기

  • dirs: 해당 path가 가지고 있는 폴더 list형식으로 반환
  • files: 해당 path내에 존재하는 files를 list형식으로 반환
import os

PATH = os.path.dirname(os.path.abspath(__file__))
dir_name = 'data'

for path, dirs, files in os.walk(os.path.join(PATH,dir_name)):
	print(path, dirs, files)

결과 :

예제 2): 폴더 내의 모든 경로 구하기

import os

PATH = os.path.dirname(os.path.abspath(__file__))
dir_name = 'data'
dir_path = os.path.join(PATH, dir_name)
for path, dirs, files in os.walk(dir_path):
	print(path)
    for file in files:
    	file_path = os.path.join(path, file)
        print(file_path)

결과 :

예제 3): 특정 확장자 추출

import os

PATH = os.path.dirname(os.path.abspath(__file__))
dir_name = 'data'

for path, dirs, files in os.walk(os.path.join(PATH,dir_name)):
    for file in files:
	    name, ext = os.path.splitext(file)
        if ext == '.png':
        	tile_path = os.path.join(os.path.join(PATH,dir_name), file)
            print('find file :',file_path)

결과 :

참고 : https://jvvp.tistory.com/986

profile
github: https://github.com/WKlee0607

0개의 댓글