문제

모든 하위 디렉토리에서 index.tpl을 index.html에 복사하는 간단한 Python 스크립트를 작성하려고합니다 (몇 가지 예외 포함).

하위 디렉토리 목록을 얻으려고 노력하여 멍청이가 발생합니다.

도움이 되었습니까?

해결책

import os
def get_immediate_subdirectories(a_dir):
    return [name for name in os.listdir(a_dir)
            if os.path.isdir(os.path.join(a_dir, name))]

다른 팁

왜 아무도 언급하지 않았습니다 glob? glob Unix 스타일의 PathName 확장을 사용할 수 있으며 하나 이상의 경로 이름을 찾는 데 필요한 거의 모든 것을 위해 기능을 수행 할 수 있습니다. 매우 쉽게 만듭니다.

from glob import glob
paths = glob('*/')

주목하십시오 glob 대부분의 반면 최종 슬래시로 디렉토리를 반환합니다. path 기반 솔루션은 최종 슬래시를 생략합니다.

확인하다 "현재 디렉토리에서 모든 하위 디렉토리 목록 얻기".

Python 3 버전은 다음과 같습니다.

import os

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

print(dir_list)
import os, os.path

디렉토리에서 즉각적인 하위 디렉토리를 얻으려면 :

def SubDirPath (d):
    return filter(os.path.isdir, [os.path.join(d,f) for f in os.listdir(d)])

최신 (최신) 하위 디렉토리를 얻으려면 :

def LatestDirectory (d):
    return max(SubDirPath(d), key=os.path.getmtime)

os.walk 이 상황에서 당신의 친구입니다.

문서에서 바로 :

Walk ()는 나무를 위 또는 아래쪽으로 걸어 가면서 디렉토리 트리에서 파일 이름을 생성합니다. 디렉토리 상단 (상단 자체 포함)에 뿌리를 둔 트리의 각 디렉토리에 대해 3- 튜플 (Dirpath, Dirnames, Filenames)을 생성합니다.

이 메소드는 한 번에 모두 잘 수행합니다.

from glob import glob
subd = [s.rstrip("/") for s in glob(parent_dir+"*/")]

Twisted 's FilePath 모듈 사용 :

from twisted.python.filepath import FilePath

def subdirs(pathObj):
    for subpath in pathObj.walk():
        if subpath.isdir():
            yield subpath

if __name__ == '__main__':
    for subdir in subdirs(FilePath(".")):
        print "Subdirectory:", subdir

일부 의견 제시 자들은 Twisted 's Libraries를 사용하는 이점이 무엇인지 물었 기 때문에 여기서 원래 질문을 넘어서는 것입니다.


거기 있습니다 일부 개선 된 문서 FilePath의 장점을 설명하는 지점에서; 당신은 그것을 읽고 싶을 수도 있습니다.

보다 구체적 으로이 예에서는 표준 라이브러리 버전과 달리이 기능을 구현할 수 있습니다. 수입이 없습니다. "서브 디르"기능은 그 주장만으로 작동한다는 점에서 완전히 일반적입니다. 표준 라이브러리를 사용하여 파일을 복사하고 이동하려면 "open"내장,"listdir", 아마도 "isdir" 또는 "os.walk" 또는 "shutil.copy". 아마도 "os.path.join"너무. 실제 파일을 식별하기 위해 문자열이 필요한 인수가 필요하다는 사실은 말할 것도없이 말할 것도없이. 각 디렉토리의"index.tpl "을"index.html "에 복사 할 전체 구현을 살펴 보겠습니다.

def copyTemplates(topdir):
    for subdir in subdirs(topdir):
        tpl = subdir.child("index.tpl")
        if tpl.exists():
            tpl.copyTo(subdir.child("index.html"))

위의 "서브 디르"기능은 FilePath-같은 개체. 무엇보다도 ZipPath 사물. 안타깝게도 ZipPath 지금은 읽기 전용이지만 글쓰기를 지원하기 위해 확장 될 수 있습니다.

테스트 목적으로 자신의 객체를 전달할 수도 있습니다. 여기에서 제안 된 OS.Path-using API를 테스트하기 위해서는 수입 된 이름과 암시 적 의존성을 가진 원숭이가 필요하고 일반적으로 테스트를 수행하기 위해 흑 마법을 수행해야합니다. FilePath를 사용하면 다음과 같은 일을합니다.

class MyFakePath:
    def child(self, name):
        "Return an appropriate child object"

    def walk(self):
        "Return an iterable of MyFakePath objects"

    def exists(self):
        "Return true or false, as appropriate to the test"

    def isdir(self):
        "Return true or false, as appropriate to the test"
...
subdirs(MyFakePath(...))

방금 vmware 가상 머신을 옮기기위한 코드를 작성하고 결국 사용했습니다. os.path 그리고 shutil 하위 디렉터간에 파일 복사를 수행합니다.

def copy_client_files (file_src, file_dst):
    for file in os.listdir(file_src):
            print "Copying file: %s" % file
            shutil.copy(os.path.join(file_src, file), os.path.join(file_dst, file))

매우 우아하지는 않지만 작동합니다.

다음은 다음과 같습니다.

import os
import shutil

def copy_over(path, from_name, to_name):
  for path, dirname, fnames in os.walk(path):
    for fname in fnames:
      if fname == from_name:
        shutil.copy(os.path.join(path, from_name), os.path.join(path, to_name))


copy_over('.', 'index.tpl', 'index.html')
def get_folders_in_directories_recursively(self, directory, index=0):
    folder_list = list()
    parent_directory = directory

    for path, subdirs, _ in os.walk(directory):
        if not index:
            for sdirs in subdirs:
                folder_path = "{}/{}".format(path, sdirs)
                folder_list.append(folder_path)
        elif path[len(parent_directory):].count('/') + 1 == index:
            for sdirs in subdirs:
                folder_path = "{}/{}".format(path, sdirs)
                folder_list.append(folder_path)

    return folder_list

다음 함수를 다음과 같이 호출 할 수 있습니다.

get_folders_in_directories_recursively (directory, index = 1) -> 폴더 목록을 1 단계로 제공합니다.

get_folders_in_directories_recursively (directory) -> 모든 하위 폴더를 제공합니다.

나는 언급해야한다 path.py 내가 자주 사용하는 도서관.

즉각적인 하위 디렉토리를 가져 오는 것은 다음과 같이 간단 해집니다.

my_dir.dirs()

전체 작업 예는 다음과 같습니다.

from path import Path

my_directory = Path("path/to/my/directory")

subdirs = my_directory.dirs()

NB : my_directory는 여전히 문자열로 조작 될 수 있습니다. 경로는 문자열의 서브 클래스이지만 경로를 조작하기위한 유용한 방법을 제공합니다.

import glob
import os

def child_dirs(path):
     cd = os.getcwd()        # save the current working directory
     os.chdir(path)          # change directory 
     dirs = glob.glob("*/")  # get all the subdirectories
     os.chdir(cd)            # change directory to the script original location
     return dirs

그만큼 child_dirs 함수는 디렉토리를 경로로 가져 와서 목록을 반환합니다. 즉각적인 하위 디렉터 그것에.

dir
 |
  -- dir_1
  -- dir_2

child_dirs('dir') -> ['dir_1', 'dir_2']
import pathlib


def list_dir(dir):
    path = pathlib.Path(dir)
    dir = []
    try:
        for item in path.iterdir():
            if item.is_dir():
                dir.append(item)
        return dir
    except FileNotFoundError:
        print('Invalid directory')
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top