폴더 내의 파일 검색하기
2015. 7. 10. 15:23ㆍProgramming/python
파이썬에서 폴더 안의 파일을 검색해서 처리해야 하는 일들이 종종 생긴다.
하지만 중첩된 폴더일 경우 이게 폴더도 있는 건지 파일만 있는 건지 확인도 해야하고, 생각외로 처리해야 할 것들이 많다.
간단하기 재귀로 폴더 안의 파일들을 검색하는 로직을 짜봤다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def search(path): | |
file_list = os.listdir(path) | |
for f in file_list: | |
nextfile = os.path.join(path, f) | |
if os.path.isdir(nextfile): | |
search(nextfile) | |
else: | |
print nextfile |
위와 같은 방법으로 짤 수도 있지만 python에서는 더 좋은 함수를 제공해 주고 있다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def search2(root_path): | |
for (path, dirname, files) in os.walk(root_path): | |
for f in files: | |
print path + '/' + f |
os.walk를 사용하면 코드의 간결함 뿐만 아니라 처리 속도 향상도 얻을 수가 있다.
(재귀는 좀 찝찝하기도 하고.. )