본문 바로가기

Python 및 AI개발

Python 파일 목록 및 하위폴더 목록 읽어오기

반응형

출처 : https://www.quora.com/Whats-the-easiest-way-to-recursively-get-a-list-of-all-the-files-in-a-directory-tree-in-Python

1. os.listdir()

1
2
3
4
5
6
7
8
9
10
11
12
def traverse(dirpath)
    for item in os.listdir(dirpath):    #item은 폴더거나 파일이거나 둘중 하나
            abspath = os.path.join(dirpath, item)
 
            try:
                if os.path.isdir(abspath):  #폴더인경우
                    traverse(abspath)
                else:                       #파일인 경우
                    dosomething(dirpath, item)
 
            except FileNotFoundError as err:
                print('잘못된 폴더\n''Error: ', err)

2. glob.glob() - command shell 스타일의 와일드 카드 사용가능
 ※ 윈도우즈에서 긴 파일명이나 긴 폴더명 사용시 에러발생함. 마법코드 \\?\을 사용하라는데....
   
시도는 해보았으나 해결못함

1
2
3
4
    import glob
    dirList = glob.glob("/Users/adityasingh/Documents/Dev/*.py")
    for d in dirList:
     print d

3. os.walk() - 모든 폴더와 하위 폴더를 recursive하게 가져옴

1
2
3
4
5
6
    from os import walk
    f = []
    path ="/Users/adityasingh/Documents/Dev"
    for (dirpath, dirnames, filenames) in walk(path):
     print dirnames
     break
 
반응형

'Python 및 AI개발' 카테고리의 다른 글

ModuleNotFound 에러를 만났을때  (0) 2021.05.22