파이썬에서 최고 레벨 디렉토리 만 나열하는 방법은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/141291

  •  02-07-2019
  •  | 
  •  

문제

일부 폴더 내부에 디렉토리 만 나열 할 수 있기를 원합니다. 이것은 내가 파일 이름을 나열하고 싶지 않으며 추가 하위 폴더를 원하지 않음을 의미합니다.

예제가 도움이되는지 봅시다. 현재 디렉토리에는 다음과 같습니다.

>>> os.listdir(os.getcwd())
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'mod_p
ython-wininst.log', 'NEWS.txt', 'pymssql-wininst.log', 'python.exe', 'pythonw.ex
e', 'README.txt', 'Removemod_python.exe', 'Removepymssql.exe', 'Scripts', 'tcl',
 'Tools', 'w9xpopen.exe']

그러나 나는 파일 이름을 나열하고 싶지 않습니다. 또한 lib curses와 같은 하위 폴더도 원하지 않습니다. 본질적으로 내가 원하는 것은 다음과 함께 작동합니다.

>>> for root, dirnames, filenames in os.walk('.'):
...     print dirnames
...     break
...
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'Scripts', 'tcl', 'Tools']

그러나 동일한 결과를 달성하는 더 간단한 방법이 있는지 궁금합니다. OS.Walk를 사용하여 최상위 레벨을 반환하는 것이 비효율적이거나 너무 많다는 인상을받습니다.

도움이 되었습니까?

해결책

os.path.isdir ()를 사용하여 결과를 필터링하고 (os.path.join ()을 사용하여 실제 경로를 얻습니다) :

>>> [ name for name in os.listdir(thedir) if os.path.isdir(os.path.join(thedir, name)) ]
['ctypes', 'distutils', 'encodings', 'lib-tk', 'config', 'idlelib', 'xml', 'bsddb', 'hotshot', 'logging', 'doc', 'test', 'compiler', 'curses', 'site-packages', 'email', 'sqlite3', 'lib-dynload', 'wsgiref', 'plat-linux2', 'plat-mac']

다른 팁

OS. 워크

사용 os.walk ~와 함께 next 항목 기능 :

next(os.walk('.'))[1]

을 위한 Python <= 2.5 사용:

os.walk('.').next()[1]

이것이 어떻게 작동하는지

os.walk 발전기와 호출입니다 next 3- 튜플 (Dirpath, Dirnames, Filenames) 형태로 첫 번째 결과를 얻습니다. 그래서 [1] 색인 만 반환합니다 dirnames 그 튜플에서.

os.path.isdir를 사용하여 목록을 필터링하여 디렉토리를 감지하십시오.

filter(os.path.isdir, os.listdir(os.getcwd()))
directories=[d for d in os.listdir(os.getcwd()) if os.path.isdir(d)]

그렇게하는 대신에 주목하십시오 os.listdir(os.getcwd()), 바람직합니다 os.listdir(os.path.curdir). 기능 호출이 적고 휴대용입니다.

따라서 답을 작성하려면 폴더에서 디렉토리 목록을 얻으려면 다음과 같습니다.

def listdirs(folder):
    return [d for d in os.listdir(folder) if os.path.isdir(os.path.join(folder, d))]

전체 PathNames를 선호하는 경우이 기능을 사용하십시오.

def listdirs(folder):
    return [
        d for d in (os.path.join(folder, d1) for d1 in os.listdir(folder))
        if os.path.isdir(d)
    ]

os.listdir ()를 사용하여 추가하려면 "매우 간단한 os.walk (). next () [1]을 많이 처리합니다.". os.walk ()는 내부적으로 os.listdir ()를 사용하기 때문입니다. 실제로 함께 테스트하면 :

>>>> import timeit
>>>> timeit.timeit("os.walk('.').next()[1]", "import os", number=10000)
1.1215229034423828
>>>> timeit.timeit("[ name for name in os.listdir('.') if os.path.isdir(os.path.join('.', name)) ]", "import os", number=10000)
1.0592019557952881

os.listdir ()의 필터링은 매우 빠릅니다.

매우 간단하고 우아한 방법은 이것을 사용하는 것입니다.

 import os
 dir_list = os.walk('.').next()[1]
 print dir_list

폴더 이름을 원하는 동일한 폴더 에서이 스크립트를 실행합니다. 폴더의 전체 경로가없는 즉각적인 폴더 이름 만 정확히 제공합니다.

이것은 (적어도 Linux에서) 작동하는 것 같습니다.

import glob, os
glob.glob('*' + os.path.sep)

여기서 초보자이기 때문에 아직 직접 언급 할 수는 없지만 여기에 다음 부분에 추가하고 싶은 작은 수정이 있습니다. τζωτζιου의 답변 :

전체 PathNames를 선호하는 경우이 기능을 사용하십시오.

def listdirs(folder):  
  return [
    d for d in (os.path.join(folder, d1) for d1 in os.listdir(folder))
    if os.path.isdir(d)
]

여전히 Python <2.4에있는 사람들을 위해: 내부 구성은 튜플 대신 목록이어야하므로 다음과 같이 읽어야합니다.

def listdirs(folder):  
  return [
    d for d in [os.path.join(folder, d1) for d1 in os.listdir(folder)]
    if os.path.isdir(d)
  ]

그렇지 않으면 구문 오류가 발생합니다.

목록 이해력 사용,

[a for a in os.listdir() if os.path.isdir(a)]

나는 그것이 가장 간단한 방법이라고 생각합니다

[x for x in os.listdir(somedir) if os.path.isdir(os.path.join(somedir, x))]

전체 경로 이름 목록의 경우이 버전을 다른 버전보다 선호합니다. 솔루션 여기:

def listdirs(dir):
    return [os.path.join(os.path.join(dir, x)) for x in os.listdir(dir) 
        if os.path.isdir(os.path.join(dir, x))]
scanDir = "abc"
directories = [d for d in os.listdir(scanDir) if os.path.isdir(os.path.join(os.path.abspath(scanDir), d))]

디렉토리가 없을 때 실패하지 않는 안전한 옵션.

def listdirs(folder):
    if os.path.exists(folder):
         return [d for d in os.listdir(folder) if os.path.isdir(os.path.join(folder, d))]
    else:
         return []

그렇게?

>>>> [path for path in os.listdir(os.getcwd()) if os.path.isdir(path)]
-- This will exclude files and traverse through 1 level of sub folders in the root

def list_files(dir):
    List = []
    filterstr = ' '
    for root, dirs, files in os.walk(dir, topdown = True):
        #r.append(root)
        if (root == dir):
            pass
        elif filterstr in root:
            #filterstr = ' '
            pass
        else:
            filterstr = root
            #print(root)
            for name in files:
                print(root)
                print(dirs)
                List.append(os.path.join(root,name))
            #print(os.path.join(root,name),"\n")
                print(List,"\n")

    return List
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top