programing

현재 디렉토리의 모든 하위 디렉토리 목록 가져오기

sourcejob 2022. 9. 25. 00:20
반응형

현재 디렉토리의 모든 하위 디렉토리 목록 가져오기

Python의 현재 디렉토리에 있는 모든 서브디렉토리 목록을 반환하는 방법이 있습니까?

파일로 할 수 있다는 건 알지만, 대신 디렉토리 목록을 가져와야 해요.

즉시 서브디렉토리, 아니면 트리 바로 아래에 있는 모든 디렉토리를 말하는 건가요?

어느 쪽이든, 를 사용해 다음과 같이 할 수 있습니다.

os.walk(directory)

는 각 서브디렉토리에 대해 태플을 생성합니다.3-태플의 첫 번째 엔트리는 디렉토리 이름이기 때문에

[x[0] for x in os.walk(directory)]

는 모든 서브디렉토리를 재귀적으로 제공합니다.

태플의 두 번째 엔트리는 첫 번째 위치에 있는 엔트리의 하위 디렉토리 목록이기 때문에 대신 이 엔트리를 사용할 수 있지만 큰 절약은 되지 않습니다.

다만, 다음의 서브 디렉토리를 제공하는 것만으로 사용할 수 있습니다.

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

또는 "How to get all immediate subdirectories in Python"에서 및 을 사용하여 이미 게시된 다른 솔루션을 참조하십시오.

쓰면 돼요.glob.glob

from glob import glob
glob("/path/to/directory/*/", recursive = True)

것을 /*.

위보다 훨씬 더 좋은 것은 여러 os.path.join()이 필요하지 않고 직접 전체 경로를 얻을 수 있기 때문입니다(원하는 경우). Python 3.5 이상에서 이 작업을 수행할 수 있습니다.

subfolders = [ f.path for f in os.scandir(folder) if f.is_dir() ]

그러면 하위 디렉토리에 대한 전체 경로가 제공됩니다. " " 를 합니다.f.namef.path

https://docs.python.org/3/library/os.html#os.scandir


약간 OT: 모든 서브폴더가 재귀적으로 필요한 경우 및/또는 모든 파일이 재귀적으로 필요한 경우, 이 기능을 참조하십시오.이것은, 보다 고속입니다.os.walk&glob모든 서브폴더와 그 서브폴더 내의 모든 파일의 리스트가 반환됩니다.https://stackoverflow.com/a/59803793/2441026

모든 하위 폴더만 반복적으로 원하는 경우:

def fast_scandir(dirname):
    subfolders= [f.path for f in os.scandir(dirname) if f.is_dir()]
    for dirname in list(subfolders):
        subfolders.extend(fast_scandir(dirname))
    return subfolders

전체 경로와 함께 모든 하위 폴더의 목록을 반환합니다.도 역시 , 빠르다, 빠르다.os.walk 더 빨리glob.


모든 기능의 분석

tl;dr:
- 폴더용으로 모든 서브디렉토리를 가져오고 싶은 경우os.scandir.
- 모든 서브디렉토리를 가져오려면 (네스트된 서브디렉토리까지 포함)os.walk- 더 - 는 - 간 - 약 - 른 - 른 -fast_scandir위의 기능을 수행합니다.
안 함 - 사용 안 함 - 사용 안 함os.walk 서브디렉토리의 , 「」보다 수 에, 의 서브 디렉토리만의 경우.os.scandir.

  • 다음 코드를 실행할 경우 OS가 폴더에 액세스할 수 있도록 한 번 실행한 후 결과를 파기하고 테스트를 수행합니다.그렇지 않으면 결과가 스크류됩니다.
  • 함수 호출을 혼재시키고 싶을지도 모르지만, 테스트해 본 결과, 별로 문제가 되지 않았습니다.
  • 모든 예에서 폴더의 전체 경로를 제공합니다.pathlib의 예(Windows)패스 오브젝트
  • 의 첫 os.walk기본 폴더가 됩니다.따라서 하위 디렉토리만 얻을 수 없습니다.하시면 됩니다.fu.pop(0)제거할 수 있습니다.
  • 어떤 결과도 자연 정렬을 사용하지 않습니다.즉, 결과는 1, 10, 2와 같이 정렬됩니다.내추럴 정렬(1, 2, 10)은 https://stackoverflow.com/a/48030307/2441026을 참조하십시오.


결과:

os.scandir      took   1 ms. Found dirs: 439
os.walk         took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob       took  20 ms. Found dirs: 439
pathlib.iterdir took  18 ms. Found dirs: 439
os.listdir      took  18 ms. Found dirs: 439

3. W7x64, Python 3.8.1에서 테스트 .

# -*- coding: utf-8 -*-
# Python 3


import time
import os
from glob import glob
from pathlib import Path


directory = r"<insert_folder>"
RUNS = 1


def run_os_walk():
    a = time.time_ns()
    for i in range(RUNS):
        fu = [x[0] for x in os.walk(directory)]
    print(f"os.walk\t\t\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len(fu)}")


def run_glob():
    a = time.time_ns()
    for i in range(RUNS):
        fu = glob(directory + "/*/")
    print(f"glob.glob\t\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len(fu)}")


def run_pathlib_iterdir():
    a = time.time_ns()
    for i in range(RUNS):
        dirname = Path(directory)
        fu = [f for f in dirname.iterdir() if f.is_dir()]
    print(f"pathlib.iterdir\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len(fu)}")


def run_os_listdir():
    a = time.time_ns()
    for i in range(RUNS):
        dirname = Path(directory)
        fu = [os.path.join(directory, o) for o in os.listdir(directory) if os.path.isdir(os.path.join(directory, o))]
    print(f"os.listdir\t\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len(fu)}")


def run_os_scandir():
    a = time.time_ns()
    for i in range(RUNS):
        fu = [f.path for f in os.scandir(directory) if f.is_dir()]
    print(f"os.scandir\t\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms.\tFound dirs: {len(fu)}")


if __name__ == '__main__':
    run_os_scandir()
    run_os_walk()
    run_glob()
    run_pathlib_iterdir()
    run_os_listdir()
import os

d = '.'
[os.path.join(d, o) for o in os.listdir(d) 
                    if os.path.isdir(os.path.join(d,o))]

Python 3.4는 파일 시스템 경로를 처리하기 위한 객체 지향 접근 방식을 제공하는 표준 라이브러리에 모듈을 도입했습니다.

from pathlib import Path

p = Path('./')

# All subdirectories in the current directory, not recursive.
[f for f in p.iterdir() if f.is_dir()]

모든 서브디렉토리를 재귀적으로 리스트 하려면 패턴과 함께 패스글로빙을 사용할 수 있습니다.

# This will also include the current directory '.'
list(p.glob('**'))

의 「」: 「」가 있는 해 주세요.*글로벌 패턴에는 파일과 디렉토리가 비연속적으로 포함되기 때문입니다.하려면 , 「」( 「」)을 참조해 ./할 수 이는 직접 통해 하지 않습니다.

import glob

# These three lines return both files and directories
list(p.glob('*'))
list(p.glob('*/'))
glob.glob('*')

# Whereas this returns only directories
glob.glob('*/')

★★★★★★★★★★★★★★★★★.Path('./').glob('**')는 같은 합니다.glob.glob('**/', recursive=True).

Pathlib은 PyPi의 pathlib2 모듈을 통해 Python 2.7에서도 사용할 수 있습니다.

하위 디렉토리의 모든 하위 디렉토리를 찾는 재귀 솔루션이 필요한 경우 이전에 제안한 대로 walk를 사용하십시오.

디렉토리의 는, 「」를 조합해 .os.listdiros.path.isdir

디렉토리만 목록 표시

print("\nWe are listing out only the directories in current directory -")
directories_in_curdir = list(filter(os.path.isdir, os.listdir(os.curdir)))
print(directories_in_curdir)

목록 현재 디렉터리에 있는 파일만 출력

files = list(filter(os.path.isfile, os.listdir(os.curdir)))
print("\nThe following are the list of all files in the current directory -")
print(files)

저는 필터(https://docs.python.org/2/library/functions.html#filter),)를 사용하는 것을 선호하지만, 이것은 단지 취향의 문제입니다.

d='.'
filter(lambda x: os.path.isdir(os.path.join(d, x)), os.listdir(d))

python-os-walk를 사용하여 구현했습니다.(http://www.pythonforbeginners.com/code-snippets-source-code/python-os-walk/)

import os

print("root prints out directories only from what you specified")
print("dirs prints out sub-directories from root")
print("files prints out all files from root and directories")
print("*" * 20)

for root, dirs, files in os.walk("/var/log"):
    print(root)
    print(dirs)
    print(files)

Python 2.7에서 os.listdir(path)를 사용하여 하위 디렉토리(및 파일) 목록을 가져올 수 있습니다.

import os
os.listdir(path)  # list of subdirectories and files

Python 3.4 및 Windows UNC 경로에서 이 문제를 발견했으므로, 이 환경에 맞는 변형은 다음과 같습니다.

from pathlib import WindowsPath

def SubDirPath (d):
    return [f for f in d.iterdir() if f.is_dir()]

subdirs = SubDirPath(WindowsPath(r'\\file01.acme.local\home$'))
print(subdirs)

Pathlib은 Python 3.4에서 처음 등장하여 다양한 OS에서 경로 조작을 훨씬 쉽게 합니다.https://docs.python.org/3.4/library/pathlib.html

이 질문은 오래전에 답해줬지만.이 모듈은 Windows 및 Unix OS에서 사용할 수 있는 강력한 방법이기 때문에 추천합니다.

따라서 서브디렉토리를 포함한 특정 디렉토리내의 모든 패스를 취득하려면 , 다음의 순서에 따릅니다.

from pathlib import Path
paths = list(Path('myhomefolder', 'folder').glob('**/*.txt'))

# all sorts of operations
file = paths[0]
file.name
file.stem
file.parent
file.suffix

기타.

복사 붙여넣기 위치ipython:

import os
d='.'
folders = list(filter(lambda x: os.path.isdir(os.path.join(d, x)), os.listdir(d)))

출력원print(folders):

['folderA', 'folderB']

조언해줘서 고마워, 여러분.소프트링크(무한재귀)가 dir로 반환되는 문제가 발생했습니다.소프트링크?냄새나는 소프트 링은 필요 없어!그래서...

이는 소프트링크가 아닌 dirs만 렌더링했습니다.

>>> import os
>>> inf = os.walk('.')
>>> [x[0] for x in inf]
['.', './iamadir']

다음은 @Blair Conrad의 예를 기반으로 한 몇 가지 간단한 함수입니다.

import os

def get_subdirs(dir):
    "Get a list of immediate subdirectories"
    return next(os.walk(dir))[1]

def get_subfiles(dir):
    "Get a list of immediate subfiles"
    return next(os.walk(dir))[2]

이렇게 하는 거예요.

    import os
    for x in os.listdir(os.getcwd()):
        if os.path.isdir(x):
            print(x)

Eli Bendersky의 솔루션을 기반으로 다음 예를 사용합니다.

import os
test_directory = <your_directory>
for child in os.listdir(test_directory):
    test_path = os.path.join(test_directory, child)
    if os.path.isdir(test_path):
        print test_path
        # Do stuff to the directory "test_path"

어디에<your_directory>는, 트래버스 하는 디렉토리의 패스입니다.

전체 경로 및 경로 계정 사용.,..,\\,..\\..\\subfolder등:

import os, pprint
pprint.pprint([os.path.join(os.path.abspath(path), x[0]) \
    for x in os.walk(os.path.abspath(path))])

가장 쉬운 방법:

from pathlib import Path
from glob import glob

current_dir = Path.cwd()
all_sub_dir_paths = glob(str(current_dir) + '/*/') # returns list of sub directory paths

all_sub_dir_names = [Path(sub_dir).name for sub_dir in all_sub_dir_paths] 

이 대답은 이미 존재하지 않는 것 같았다.

directories = [ x for x in os.listdir('.') if os.path.isdir(x) ]

최근에 비슷한 질문을 한 적이 있는데, python 3.6에 대한 가장 좋은 대답은 (사용자 havlock이 추가했듯이) 사용하는 것이라는 것을 알게 되었습니다.os.scandir그것을 사용하는 방법은 없는 것 같기 때문에, 제 것을 추가합니다.첫째, 루트 디렉터리 바로 아래에 하위 디렉터리만 나열하는 비재귀적 솔루션입니다.

def get_dirlist(rootdir):

    dirlist = []

    with os.scandir(rootdir) as rit:
        for entry in rit:
            if not entry.name.startswith('.') and entry.is_dir():
                dirlist.append(entry.path)

    dirlist.sort() # Optional, in case you want sorted directory names
    return dirlist

재귀 버전은 다음과 같습니다.

def get_dirlist(rootdir):

    dirlist = []

    with os.scandir(rootdir) as rit:
        for entry in rit:
            if not entry.name.startswith('.') and entry.is_dir():
                dirlist.append(entry.path)
                dirlist += get_dirlist(entry.path)

    dirlist.sort() # Optional, in case you want sorted directory names
    return dirlist

을 명심하다entry.path서브디렉토리에 대한 절대 패스를 휘두릅니다.폴더 이름만 필요한 경우 다음을 사용할 수 있습니다.entry.name대신.os를 참조해 주세요.DirEntry에 대한 자세한 내용은entry물건.

파일 트리 바로 아래에 모든 하위 디렉토리가 나열됩니다.

import pathlib


def list_dir(dir):
    path = pathlib.Path(dir)
    dir = []
    try:
        for item in path.iterdir():
            if item.is_dir():
                dir.append(item)
                dir = dir + list_dir(item)
        return dir
    except FileNotFoundError:
        print('Invalid directory')

pathlib버전 3.4의 새로운 기능

지정된 파일 경로 내의 모든 하위 디렉터리 목록을 반환하는 함수입니다.전체 파일 트리를 검색합니다.

import os

def get_sub_directory_paths(start_directory, sub_directories):
    """
    This method iterates through all subdirectory paths of a given 
    directory to collect all directory paths.

    :param start_directory: The starting directory path.
    :param sub_directories: A List that all subdirectory paths will be 
        stored to.
    :return: A List of all sub-directory paths.
    """

    for item in os.listdir(start_directory):
        full_path = os.path.join(start_directory, item)

        if os.path.isdir(full_path):
            sub_directories.append(full_path)

            # Recursive call to search through all subdirectories.
            get_sub_directory_paths(full_path, sub_directories)

return sub_directories

사용, os walk

sub_folders = []
for dir, sub_dirs, files in os.walk(test_folder):
    sub_folders.extend(sub_dirs)

필터 기능을 사용하다os.path.isdir에 걸쳐서os.listdir()와 것filter(os.path.isdir,[os.path.join(os.path.abspath('PATH'),p) for p in os.listdir('PATH/')])

는 특정 부모 '''를 가진 입니다.directory하여 말하다directories 및 '재귀적'prints 것.filenames 유용해요무무유유유유다다

import os

def printDirectoryFiles(directory):
   for filename in os.listdir(directory):  
        full_path=os.path.join(directory, filename)
        if not os.path.isdir(full_path): 
            print( full_path + "\n")


def checkFolders(directory):

    dir_list = next(os.walk(directory))[1]

    #print(dir_list)

    for dir in dir_list:           
        print(dir)
        checkFolders(directory +"/"+ dir) 

    printDirectoryFiles(directory)       

main_dir="C:/Users/S0082448/Desktop/carpeta1"

checkFolders(main_dir)


input("Press enter to exit ;")

os.walk()사용하면 모든 폴더 목록을 얻을 수 있습니다.

import os

path = os.getcwd()

pathObject = os.walk(path)

pathObject는 객체이며 다음 방법으로 어레이를 가져올 수 있습니다.

arr = [x for x in pathObject]

arr is of type [('current directory', [array of folder in current directory], [files in current directory]),('subdirectory', [array of folder in subdirectory], [files in subdirectory]) ....]

arr을 반복하고 중간 배열을 인쇄하면 모든 하위 디렉토리의 목록을 얻을 수 있습니다.

for i in arr:
   for j in i[1]:
      print(j)

모든 서브디렉토리가 인쇄됩니다.

모든 파일을 가져오려면:

for i in arr:
   for j in i[2]:
      print(i[0] + "/" + j)

여기서부터의 복수의 솔루션에의 참가에 의해서, 다음과 같은 것을 사용할 수 있게 되었습니다.

import os
import glob

def list_dirs(path):
    return [os.path.basename(x) for x in filter(
        os.path.isdir, glob.glob(os.path.join(path, '*')))]

좋은 답변이 많지만 모든 파일 또는 폴더 목록을 한 번에 얻을 수 있는 간단한 방법을 찾고 있다면.os.walk보다 훨씬 빠르고 Linux 및 Mac에서 제공되는 find os를 이용할 수 있습니다.

import os
all_files_list = os.popen("find path/to/my_base_folder -type f").read().splitlines()
all_sub_directories_list = os.popen("find path/to/my_base_folder -type d").read().splitlines()

또는

import os

def get_files(path):
    all_files_list = os.popen(f"find {path} -type f").read().splitlines()
    return all_files_list

def get_sub_folders(path):
    all_sub_directories_list = os.popen(f"find {path} -type d").read().splitlines()
    return all_sub_directories_list

아래 클래스는 지정된 디렉토리 내의 파일, 폴더 및 모든 하위 폴더 목록을 가져올 수 있습니다.

import os
import json

class GetDirectoryList():
    def __init__(self, path):
        self.main_path = path
        self.absolute_path = []
        self.relative_path = []


    def get_files_and_folders(self, resp, path):
        all = os.listdir(path)
        resp["files"] = []
        for file_folder in all:
            if file_folder != "." and file_folder != "..":
                if os.path.isdir(path + "/" + file_folder):
                    resp[file_folder] = {}
                    self.get_files_and_folders(resp=resp[file_folder], path= path + "/" + file_folder)
                else:
                    resp["files"].append(file_folder)
                    self.absolute_path.append(path.replace(self.main_path + "/", "") + "/" + file_folder)
                    self.relative_path.append(path + "/" + file_folder)
        return resp, self.relative_path, self.absolute_path

    @property
    def get_all_files_folder(self):
        self.resp = {self.main_path: {}}
        all = self.get_files_and_folders(self.resp[self.main_path], self.main_path)
        return all

if __name__ == '__main__':
    mylib = GetDirectoryList(path="sample_folder")
    file_list = mylib.get_all_files_folder
    print (json.dumps(file_list))

반면 샘플 디렉토리는

sample_folder/
    lib_a/
        lib_c/
            lib_e/
                __init__.py
                a.txt
            __init__.py
            b.txt
            c.txt
        lib_d/
            __init__.py
        __init__.py
        d.txt
    lib_b/
        __init__.py
        e.txt
    __init__.py

결과 취득

[
  {
    "files": [
      "__init__.py"
    ],
    "lib_b": {
      "files": [
        "__init__.py",
        "e.txt"
      ]
    },
    "lib_a": {
      "files": [
        "__init__.py",
        "d.txt"
      ],
      "lib_c": {
        "files": [
          "__init__.py",
          "c.txt",
          "b.txt"
        ],
        "lib_e": {
          "files": [
            "__init__.py",
            "a.txt"
          ]
        }
      },
      "lib_d": {
        "files": [
          "__init__.py"
        ]
      }
    }
  },
  [
    "sample_folder/lib_b/__init__.py",
    "sample_folder/lib_b/e.txt",
    "sample_folder/__init__.py",
    "sample_folder/lib_a/lib_c/lib_e/__init__.py",
    "sample_folder/lib_a/lib_c/lib_e/a.txt",
    "sample_folder/lib_a/lib_c/__init__.py",
    "sample_folder/lib_a/lib_c/c.txt",
    "sample_folder/lib_a/lib_c/b.txt",
    "sample_folder/lib_a/lib_d/__init__.py",
    "sample_folder/lib_a/__init__.py",
    "sample_folder/lib_a/d.txt"
  ],
  [
    "lib_b/__init__.py",
    "lib_b/e.txt",
    "sample_folder/__init__.py",
    "lib_a/lib_c/lib_e/__init__.py",
    "lib_a/lib_c/lib_e/a.txt",
    "lib_a/lib_c/__init__.py",
    "lib_a/lib_c/c.txt",
    "lib_a/lib_c/b.txt",
    "lib_a/lib_d/__init__.py",
    "lib_a/__init__.py",
    "lib_a/d.txt"
  ]
]

언급URL : https://stackoverflow.com/questions/973473/getting-a-list-of-all-subdirectories-in-the-current-directory

반응형