티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

os.walk without digging into directories below

os.walk() 함수를 이용하여 하위 디렉토리를 탐색하지 않고 현재 디렉토리 내 파일들만 검색하기

 문제 내용 

How do I limit os.walk to only return files in the directory I provide it?

os.walk() 함수를 이용하여 하위 디렉토리를 탐색하지 않고 현재 디렉토리 내 파일들만 검색하려면 어떻게 해야 하나요?
def _dir_list(self, dir_name, whitelist):
    outputList = []
    for root, dirs, files in os.walk(dir_name):
        for f in files:
            if os.path.splitext(f)[1] in whitelist:
                outputList.append(os.path.join(root, f))
            else:
                self._email_to_("ignore")
    return outputList

 

 

 높은 점수를 받은 Solution 

Don't use os.walk.

os.walk() 함수를 사용하지 마세요.

 

Example:

예:
import os

root = "C:\\"
for item in os.listdir(root):
    if os.path.isfile(os.path.join(root, item)):
        print item

 

 

 가장 최근 달린 Solution 

Since Python 3.5 you can use os.scandir instead of os.listdir. Instead of strings you get an iterator of DirEntry objects in return. From the docs:

Python 3.5 이상에서는 os.listdir 대신 os.scandir를 사용할 수 있습니다. 이 함수는 문자열 대신 DirEntry 객체의 이터레이터를 반환합니다. 문서에서는 다음과 같이 설명합니다:

 

Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type or file attribute information, because DirEntry objects expose this information if the operating system provides it when scanning a directory. All DirEntry methods may perform a system call, but is_dir() and is_file() usually only require a system call for symbolic links; DirEntry.stat() always requires a system call on Unix but only requires one for symbolic links on Windows.

scandir() 함수를 사용하면 디렉토리를 스캔할 때 운영 체제가 파일 형식 또는 파일 속성 정보를 제공하는 경우 DirEntry 객체가 이 정보를 노출하기 때문에 파일 유형이나 파일 속성 정보가 필요한 코드의 성능을 크게 향상시킬 수 있습니다. DirEntry의 모든 메소드는 시스템 호출을 수행할 수 있지만, is_dir()와 is_file()는 일반적으로 심볼릭 링크에 대해서만 시스템 호출이 필요하며, DirEntry.stat()은 Unix에서 항상 시스템 호출이 필요하지만 Windows에서는 심볼릭 링크에 대해서만 필요합니다.

 

You can access the name of the object via DirEntry.name which is then equivalent to the output of os.listdir

현재 객체의 이름은 DirEntry.name을 통해 액세스할 수 있으며, 이는 os.listdir의 출력과 동일합니다.

 

 

 

출처 : https://stackoverflow.com/questions/229186/os-walk-without-digging-into-directories-below

반응형
댓글
공지사항
최근에 올라온 글