티스토리 뷰

Programming/python

os.path.isdir/isfile 사용하기

tech_curioso 2019. 4. 1. 13:34
728x90
반응형

폴더 내의 파일 리스트를 찾는 파이썬 명령어로 os 라이브러리의 os.path.listdir를 사용한다. 다음과 같이 특정 폴더 path안의 내용을 보여준다.

import os

DATA_DIR='0417'
itemList = []
for item in os.listdir(DATA_DIR):
    itemList.append(item)

print(itemList)

 

문제는 다음과 같이 폴더 속에 폴더들 파일들이 섞여 있고 필요한 파일들이 섞여 있는 경우가 많다. 

위의 코드를 실행하면 다음과 같이 폴더의 모든 내용이 구분없이 리스트에 저장되어 있는 것을 알 수 있다. 

['417_6_4.csv', '417_6_2.mp4', '417_6_23.csv', 'desktop.ini', '417_6_21.mp4', '417_6_23.mp4', '417_6_24.mp4', '417_6_1.mp4', '417_6_5.mp4', '417_6_25.csv', '417_6_3.csv', '417_6_7.mp4', '417_6_4.mp4', '417_6_10 (1)', '417_6_2', '417_6_21', '417_6_8.csv', '417_6_8.mp4', '417_6_9.mp4', '417_6_9.csv', '417_6_6.mp4', '417_6_25.mp4', '417_6_3', '417_6_1.csv', '417_6_10', '417_6_21.csv', '0417.zip', '417_6_1', '417_6_2.csv', '417_6_24.csv', '417_6_9', '417_6_23', '417_6_25', '417_6_6.csv', '417_6_10.mp4', '417_6_4', '417_6_3.mp4', '417_6_7.csv', '417_6_7', '417_6_8', '417_6_6', '417_6_5.csv', '417_6_5', '417_6_10.csv', '417_6_24']

실제 원하는 파일들을 골라내거나 디렉토리와 파일을 분리해서 처리해야 할 때 필요한 함수들은 다음과 같다. 

  • os.path.isdir 
  • os.path.isfile
  • os.path.islink

참조: https://docs.python.org/3/library/os.path.html

 

os.path — Common pathname manipulations — Python 3.7.3 documentation

os.path — Common pathname manipulations Source code: Lib/posixpath.py (for POSIX), Lib/ntpath.py (for Windows NT), and Lib/macpath.py (for Macintosh) This module implements some useful functions on pathnames. To read or write files see open(), and for acce

docs.python.org

함수에 대한 입력이 모두 패스이므로 os.path.join을 이용하여 폴더이름과 리스트에 존재하는 파일/디렉토리 이름을 붙여서 검색해야한다.  이 부분을 몰라 많는 사람들이 나처럼 혼동하는 듯 하다. 다음 링크에 가보면 많은 사람들이 제대로 동작하지 않음을 물어보고 있다. 

https://stackoverflow.com/questions/17893542/why-do-os-path-isfile-return-false/17893555

 

Why do os.path.isfile return False?

I am just a newbie in python, so sorry for noobish question >>> import os >>> os.listdir("/home/user/Desktop/1") ['1.txt', '2', '3.txt'] >>> os.path.isfile("/home/user/D...

stackoverflow.com

다음 코드는 폴더 속에 폴더인 경우만 골라 리스트로 만드는 간단한 코드이다.

import os

DATA_DIR = "0417"
itemList = []
for item in os.listdir(DATA_DIR):        
    if os.path.isdir(os.path.join(DATA_DIR,item)):
        itemList.append(item)

print(itemList)

실행결과는 다음과 같이 폴더 이름만 리스트에 저장된 결과가 출력된 것을 알 수 있다. 

['417_6_10 (1)', '417_6_2', '417_6_21', '417_6_3', '417_6_10', '417_6_1', '417_6_9', '417_6_23', '417_6_25', '417_6_4', '417_6_7', '417_6_8', '417_6_6', '417_6_5', '417_6_24']

 

자료를 찾아보던 중 이러한 과정을 조금더 고급(?) 기법을 사용하여 간단히 정리하는 코드로 바꾸는 것에 관한 자료를 찾게 되었다.

https://dzone.com/articles/listing-a-directory-with-python

 

Listing a Directory With Python - DZone Performance

If you're a web dev and a Python lover, read on to learn how to use Python to search for and list contents of a directory, even if those files aren't in Python.

dzone.com

 

먼저 한줄로 위의 과정을 정리해서 디렉토리들만 items라는 리스트로 만드는 코드는 다음과 같다.

import os

DATA_DIR = "0417"
items =[item for item in os.listdir(DATA_DIR) if os.path.isdir(os.path.join(DATA_DIR,item))]
print(items)

결과는 앞의 코드와 동일하다.

 

또한 filter 함수를 사용하여 좀 더 깔끔하게 정리할 수 있다. 

import os

DATA_DIR = "0417"
items = (list(filter(lambda x: os.path.isdir(os.path.join(DATA_DIR,x)), os.listdir(DATA_DIR))))

print(items)

 

역시 결과도 동일하다.

 

참고한 filter관련 참고자료는 다음과 같다.

 

https://wayhome25.github.io/cs/2017/04/03/cs-03/

 

강의노트 03. 파이썬 lambda, map, filter, reduce, dic · 초보몽키의 개발공부로그

패스트캠퍼스 컴퓨터공학 입문 수업을 듣고 중요한 내용을 정리했습니다. 개인공부 후 자료를 남기기 위한 목적임으로 내용 상에 오류가 있을 수 있습니다.

wayhome25.github.io

 

728x90
반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함